Constructor Chaining in Java

  • 0
     In the professional language, A constructor is a subroutine which is called at the time of creation of object of a class. Well, Constructor is a very special method that does not has a return type, not even void. The job of this special method is to initialise the object with default values. If you don't create it explicitly, Java does it for you. This special method is called as soon as an instance of the class.
     Constructor chaining is an important concept of Inheritance.In here, we will also examine the reason for why super() must be the first statement in the constructor of the subclass. In multilevel inheritance, constructors are called in the order of derivation. This means that first the constructor of that class would be called who lies on the top of inheritance hierarchy. First statement in the constructor of the subclass causes the execution of superclass constructor first, leading to calling of constructors in the order of derivation.
package ClassIllustration;

class A
{
 A()
 {
  System.out.println("Inside A's Constructor");
 }
}
class B extends A
{
 B()
 {
  System.out.println("Inside B's Constructor");
 }
}
class C extends B
{
 C()
 {
  System.out.println("Inside C's Constructor");
 }
}
class ConstructorChaining
{
 public static void main(String args[])
 {
  C obj = new C();
 }
}
To compile the program
javac -d . ConstructorChaining.java
To run the program
javac -d . ClassIllustration.ConstructorChaining
Output of this program that I received on my machine is.
Inside A's Constructor
Inside B's Constructor
Inside C's Constructor

No comments:

Post a Comment