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 类的无参数构造函数。您需要通过调用任何超级构造函数来显式定义构造函数
解决方案:-
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 。整数不会自动提升为双精度,并且您没有默认构造函数,因此您会收到编译错误。
as Asalynd 正确地提供了这个问题的答案。 您的构造函数是为类 double 定义的,但您使用整数参数调用 Num 。整数不会自动提升为双精度,并且您没有默认构造函数,因此您会收到编译错误。在构造函数中传递参数之前,您必须输入强制类型转换