繁体   English   中英

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

[英]Implicit super constructor Num() is undefined for default constructor. Must define an explicit constructor, what is the logic behind this

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()为您插入一个no-arg构造函数。

class Example{
}

class Example{

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

但是,您的类不是这种情况,因为Number类无法为Num类找到no-arg构造函数。您需要明确定义一个构造函数,并调用任何超级构造函数

解:-

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) ; 
    } 
} 

您的构造函数是为类double定义的,但您使用整数参数调用Num。 整数不会自动提升为双精度数,并且您没有默认构造函数,因此会出现编译错误。

Asalynd正确地提供了这个问题的答案。 您的构造函数是为类double定义的,但您使用整数参数调用Num。 整数不会自动提升为双精度数,并且您没有默认构造函数,因此会出现编译错误。 你必须在构造函数中传递参数之前键入强制转换

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM