constructors in Inheritance

constructors in Inheritance  

In Java, constructor of base class with no argument gets automatically called in derived class constructor. For example, output of following program is:

Base Class Constructor Called
Derived Class Constructor Called


package com.ritesh;

class base1{
public base1(){
System.out.println("I am a base constructor");
}
base1 (int a){

System.out.println("I return the value of a to be " + a);
}
static class derived extends base1{
derived(){
super(10);
System.out.println("I am the constructor of derived class");
}
}
}


public class inheritance_type1 {
public static void main(String[] args) {
//base1 sc=new base1();
base1.derived sc2=new base1.derived();



}
}


In the above program when we overload the constructor of base class using derived class then jdk will automatically call the method without argument.

So to solve the problem we use super keyword in derived constructor.


package com.ritesh;
class base2{
base2(){

System.out.println("I am a base class constructor");
}
base2(int x){
System.out.println("I return the value of x to be "+x);
}
base2(int x, int y){
System.out.println(" I return the value of x and y to be "+ x +" and "+ y);
}

static class derived extends base2{
derived(){
super(10,20);
System.out.println("I am a derived class constructor");
}
derived(int x){
super(4);
System.out.println("I return the value of a to be "+ x);
}
}
static class filetype extends derived{
filetype(){
super(10);
System.out.println("I am a filetype constructor");
}
filetype(int x){
System.out.println("I am a filetype constructor And i return the value of a "+ x);

}
}

}

public class type {
public static void main(String[] args) {
// base2 sc=new base2();
// base2.derived sc2=new base2.derived();
base2.derived.filetype s3=new base2.filetype(10);




}
}

Comments