使用super关键字的Java多重继承

问题描述 投票:0回答:5

我在我的程序中使用继承和超级函数,但是当我扩展我的类时,它显示错误消息“'cc'中没有默认构造函数。”。在第一个子类扩展并尝试生成第二个子类之后,将出现此错误消息。这是代码

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);
    }
}
java multiple-inheritance super
5个回答
0
投票

dd继承了cc,因此它必须调用cc的默认构造函数,该构造函数目前不存在。

要解决此问题,只需添加一个不带参数的构造函数

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

1
投票

您正在dd中扩展类cc。但是在dd中你没有初始化cc所拥有的任何东西而且这是错误,因为当调用dd时它正在搜索其超类的构造函数,并且当没有定义构造函数时,java将默认采用不带参数的构造函数。所以它在cc中调用该参数,但是你没有在cc中定义任何空白参数,所以它说它只有1个构造函数,你需要创建其他空白构造函数。


0
投票

cc类构造函数是

cc(int i, int j,int k) {
}

因此,你需要在super(i, j, k)中调用dd。例如:

 class dd extends cc{   
   int h;                
   dd(int i, int j,int k) {
     super(i, j, k);
   }
   void hello(){
     System.out.println("hello");
   }
 }

0
投票

你的cc类有一个带参数的构造函数:

cc(int i, int j, int k) {}

如果你想继承cc,你必须:

  • super(int i, int j, int k)构造函数中调用dd来调用cc的构造函数,传递构造函数所需的参数。
  • 或者为cc创建一个不带参数的默认构造函数:cc() {}。如果不调用super(),默认情况下将调用此构造函数。

0
投票

问题是dd扩展了cc,它有cc(int i,int j,int k)的构造函数,但是dd的构造函数不调用它。 你需要在dd中添加一个调用super(i,j,k)的构造函数。

dd的示例代码:

}
class dd extends cc{
dd(int i, int j, int k) {
super(i, j, k);
}
int h;
void hello(){
System.out.println("hello");
}
© www.soinside.com 2019 - 2024. All rights reserved.