Skip to content
Advertisement

Java inheritance using super keyword

I am using inheritance along with super function in my program ,but when I am extending my class it showing error message “There is no default constructor in ‘cc’. ” . This error message is coming after 1st subclass is extended and trying to make 2nd subclass. Here is the code

class aa{
int i=-1;
int show(){
return i;
}
} 
class bb extends aa{ 
 int i;
 bb(int g,int j){
 super.i=g;
 i=j;
 }
}

class cc extends bb {   
int j,k;
cc(int i, int j,int k) {
  super(i,j);
  super.i=i;
  this.j=j;
  this.k=k;
  }
}
 class dd extends cc{   // here the error showing 
 int h;                //" There is no default constructor in 'cc' "
 void hello(){
 System.out.println("hello");
 }
}
class SuperUseExample3 {
    public static void main(String[] args) {
        aa x = new aa();
        System.out.println("value of a = "+x.i);
        bb y = new bb(8,2);
        System.out.println("value of a in class cc = "+y.show());
        System.out.println("value of b in class bb = "+y.i);
        cc z =new cc(12,13,14);
        System.out.println("value of a in class cc = "+z.show());
        System.out.println("value of b in class cc = "+z.j);
        System.out.println("value of c in class cc = "+z.k);
    }
}

Advertisement

Answer

dd inherits cc, so it’ll have to call the default constructor of cc, which currently doesn’t exist.

To solve this, just add a constructor with no arguments

class cc extends bb {   
    int j,k;
    cc(){
        //do whatever you want
    }
    ..//rest of code
}

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement