Java使用super关键字继承

标签 java inheritance super

我在程序中使用继承和 super 函数,但是当我扩展我的类时,它显示错误消息“'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);
    }
}

最佳答案

您正在 dd 中扩展 cc 类。但是在 dd 中,您没有初始化 cc 拥有的任何内容,这就是错误,因为当调用 dd 时,它正在搜索其父类(super class)的构造函数,并且当没有定义构造函数时,java 将不带参数的构造函数作为默认值。因此它在 cc 中调用该参数,但您没有在 cc 中定义任何空白参数,因此它说它只有 1 构造函数,您需要创建其他空白构造函数。

关于Java使用super关键字继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47854309/

相关文章:

java - Jenkins plugin——引用项目插件设置中的全局插件设置

java - 如何在java中从xml实体字符串值创建不同的pojo

java stream List<Map<String,Double>> 需要根据字符串取平均值

java - 在两个类之间共享代码(使用抽象操作)

java - java parseInt异常未被捕获

python - @classmethod 与抽象基类

Scala,直接从 super 构造函数调用中调用实例方法?

java - 当 Java 类没有父类时,是否应该调用 super() ?

java - 错误: This class should provide a default constructor

c++ - 父类(super class)的指针如何访问子类的变量?