Super keyword (calling constructors)

public class Test {
	
	public static void main(String[] args)
	{
		C obj = new C();
		
	}
}


class A
{
	public A()
	{
		System.out.println("Inside A constructor");
	}
}

class B extends A
{
	public B()
	{
		System.out.println("Inside B constructor");
	}
}

class C extends B
{
	public C()
	{
		System.out.println("Inside C constructor");
	}
}

Outputs:

Inside A constructor
Inside B constructor
Inside C constructor

Why?

When constructor C is called, it actually calls constructor B, which called constructor A.

Likewise if we called constructor B, it would call constructor A.

e.g.

public class Test {
	
	public static void main(String[] args)
	{
		B obj = new B();
		
	}
}


class A
{
	public A()
	{
		System.out.println("Inside A constructor");
	}
}

class B extends A
{
	public B()
	{
		System.out.println("Inside B constructor");
	}
}

class C extends B
{
	public C()
	{
		System.out.println("Inside C constructor");
	}
}

Outputs:

Inside A constructor
Inside B constructor

In inheritance, a derived class has it’s own constructor(s), but DOESN’T inherit any constructors from the base class. The above behaviour is so that the superclass methods can be given values by the superclass constructors.

public class Test {
	
	public static void main(String[] args)
	{
		B obj = new B(2,10);
		
	}
}


class A
{
	int intA = 20;
	
	public A()
	{
		System.out.println("Inside A constructor");
	}
	
	public A(int number)
	{
		System.out.println("Inside A superclass constructor that takes one argument");
		intA = 2*number;
	}
}

class B extends A
{
	int intB = 40;
	
	public B()
	{
		System.out.println("Inside B constructor");
	}
	
	public B(int number1, int number2)
	{
		super(number1); // call the superclass constructor and pass the number1 - super must be FIRST statement
		intB = number2;
		System.out.println("intA="+intA);
		System.out.println("intB="+intB);
	}
}

Output:

Inside A superclass constructor that takes one argument
intA=4
intB=10

Leave a Reply