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 class A, with an abstract method func(), that it uses in its constructor.
  • We have also created a class B that extends A and has an int field. In its constructor it initializes its int value to a given one. It also overrides the func() method of A.
  • 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 by B, the overriden func() is called, that prints the int field of B, that is equal to 0, since it is not initialized yet. Then in B‘s constructor the int value of B becomes equal to the given value.
  • Note that if we make the abstract func() method final, then we cannot modify it in B.

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.

Ilias Tsagklis

Ilias is a software developer turned online entrepreneur. He is co-founder and Executive Editor at Java Code Geeks.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button