gpt4 book ai didi

java - 错误: Constructor A in class A cannot be applied to given types

转载 作者:行者123 更新时间:2023-12-01 07:23:58 25 4
gpt4 key购买 nike

public class A{

public A(String x){
System.out.println("A constructor Called "+x);
}
public static void main(String []args){
System.out.println("Hello World");
A a= new B("b");
}
}

class B extends A{
public B(String x){
System.out.println("B constructor Called "+x);
}
}

这个非常简单的程序有什么问题,我无法找到它。编译时出现以下错误:

A.java:13: error: constructor A in class A cannot be applied to given types;                                                                                                    
public B(String x){
^
required: String
found: no arguments
reason: actual and formal argument lists differ in length

最佳答案

由于类 A 没有默认构造函数,因此您需要告诉类 B 如何构造其父类:

class B extends A{
public B(String x){
super(x); // this constructs the parent class
System.out.println("B constructor Called "+x);
}
}

错误告诉您必须调用的构造函数需要一个字符串:

required: String

...但是您正在调用的构造函数(这是默认构造函数,因为您没有调用 super )没有参数:

found: no arguments

关于java - 错误: Constructor A in class A cannot be applied to given types,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29087973/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com