class
Polymorphism and constructors example
With this example we are going to demonstrate the polymorphism of a class and the constructors behaviour. In short, to see how constructors are used in a class and the changes that a statement can cause to a class we have performed the following steps:
- We have created an
abstract
classA
, with anabstract
methodfunc()
, that it uses in its constructor. - We have also created a class
B
that extendsA
and has anint
field. In its constructor it initializes its int value to a given one. It also overrides thefunc()
method ofA
. - We create a new instance of
B
with a given int value. - The constructor of
A
is first called. - The
func()
method is called, and since it is overriden byB
, the overridenfunc()
is called, that prints the int field ofB
, that is equal to 0, since it is not initialized yet. Then inB
‘s constructor the int value ofB
becomes equal to the given value. - Note that if we make the
abstract func()
methodfinal
, then we cannot modify it inB
.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.core; abstract class A { // Make the method func final and run again the example abstract void func(); A() { System.out.println("A() before func()"); func(); System.out.println("A() after func()"); } } class B extends A { private int value = 1; B(int val) { value = val; System.out.println("B.B(), value = " + value); } @Override void func() { System.out.println("B.func(), value = " + value); } } public class Polymorphism { public static void main(String[] args) { new B(5); } }
Output:
A() before func()
B.func(), value = 0
A() after func()
B.B(), value = 5
This was an example of polymorphism and constructors in a class in Java.