Download as pdf or txt
Download as pdf or txt
You are on page 1of 1

Java Inheritance and Constructor

author: Abhishek Nirmala Pandey


Note: The code & output are self explanatory. Hence no explanation has been provided.

Code:
Parent class:

package com.blogspot.adultsincebirth;
public class InheritConstructorParent
{
static
{
System.out.println("parent static block");
}
{
System.out.println("parent non static block, "+this.getClass());
}
public InheritConstructorParent()
{
System.out.println("parent ctor (NO parameter)");
}
public InheritConstructorParent(int x)
{
System.out.println("parent ctor (WITH parameter)");
}
}

Child class:

package com.blogspot.adultsincebirth;
public class InheritConstructorChild extends InheritConstructorParent
{
static
{
System.out.println("child static block");
}
{
System.out.println("child non static block");
}
public InheritConstructorChild()
{
System.out.println("child ctor (NO parameter)");
}
public InheritConstructorChild(int x)
{
System.out.println("Child ctor (WITH parameter)");
}
}

Test class with `main` method:

package com.blogspot.adultsincebirth;
public class InheritConstructorTest
{
public static void main(String[] args)
{
new InheritConstructorChild(0);
new InheritConstructorChild();
}
}

Output:

parent static block


child static block
parent non static block, class com.blogspot.adultsincebirth.InheritConstructorChild
parent ctor (NO parameter)
child non static block
Child ctor (WITH parameter)
parent non static block, class com.blogspot.adultsincebirth.InheritConstructorChild
parent ctor (NO parameter)
child non static block
child ctor (NO parameter)

You might also like