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:
01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | 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.