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

问题描述 投票:0回答:3
class Num 
{
    Num(double x) 
    { 
        System.out.println( x ) ; 
    }
}
class Number extends Num 
{ 
    public static void main(String[] args)
    { 
        Num num = new Num(2) ; 
    } 
} 

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

java object oop constructor
3个回答
6
投票

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

class Example{
}

变成

class Example{

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

但是,您的类的情况并非如此,因为 Number 类无法找到 Num 类的无参数构造函数。您需要通过调用任何超级构造函数来显式定义构造函数

解决方案:-

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

0
投票

您的构造函数是为类

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.