java - 默认构造函数的隐式 super 构造函数 Num() 未定义。必须定义一个显式的构造函数,这背后的逻辑是什么

标签 java oop object constructor core

class Num 
{
    Num(double x) 
    { 
        System.out.println( x ) ; 
    }
}
class Number extends Num 
{ 
    public static void main(String[] args)
    { 
        Num num = new Num(2) ; 
    } 
} 

在上面的程序中,它显示了错误。请帮帮我。

最佳答案

当您定义自己的构造函数时,编译器不会为您提供无参构造函数。 当您定义一个没有构造函数的类时,编译器会通过调用 super() 为您插入一个无参数构造函数。

class Example{
}

成为

class Example{

Example(){
super();   // an accessible no-arg constructor must be present for the class to compile.
}

但是,您的类不是这种情况,因为 Number 类找不到 Num 类的无参数构造函数。您需要通过调用任何 super 构造函数为您显式定义一个构造函数

解决方案:-

class Num 
{
    Num(double x) 
    { 
        System.out.println( x ) ; 
    }
}

class Number extends Num 
{ 


 Number(double x){
 super(x);
 }

 public static void main(String[] args)
    { 
        Num num = new Num(2) ; 
    } 
} 

关于java - 默认构造函数的隐式 super 构造函数 Num() 未定义。必须定义一个显式的构造函数,这背后的逻辑是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24995235/

相关文章:

java - 使用对象实例化作为枚举条目的值是好习惯吗?

java - JAR 隐藏在 EXE 中?

java - 为什么/如何返回 "locally instantiated array"在 Java 中工作?

java - 我应该使用什么 View 来存储音乐播放器的歌曲? ListView 还是 RecyclerView?

java - 为什么我们必须固定每次测量迭代的持续时间?

java - 如何从 JFrame 切换到 java 类?

JavaScript 错误 : object is not a function in a video poker script

javascript - 在 Angular 服务中扩展基类

c++ - 如何使客户端无法访问命名空间的函数

java - "Save transient object before flushing"错误