【问题标题】:error: constructor Name2 in class Name2 cannot be applied to given types;错误:类 Name2 中的构造函数 Name2 不能应用于给定类型;
【发布时间】:2020-04-28 12:30:48
【问题描述】:

在编码时我遇到了一些问题。 在多级继承中,cl 是 A 类和 B 类中都使用的变量,但在运行程序时会显示错误。我在下面粘贴代码。

     class Name{
    int cl=0;
}
class Name2 extends Name{
    public Name2(int cl)
    {
        this.cl=cl;
    }
    public String toString()
    {
        return String.valueOf(cl);
    }
}
class Name3 extends Name2{
    int tl;
    public Name3(int cl,int tl)
    {
        super();
        this.tl=tl;
    }
    public String toString()
    {
        return String.valueOf(cl);
    }
}

public class HelloWorld{

     public static void main(String []args){
        Name3 obj=new Name3(3,6);

        System.out.println(obj);
     }
}



  ----------------------------------

Output is:

    > $javac HelloWorld.java HelloWorld.java:18: error: constructor Name2 in
    > class Name2 cannot be applied to given types;
    >         super();
    >         ^   required: int   found: no arguments   reason: actual and formal argument lists differ in length 1 error

【问题讨论】:

    标签: java inheritance polymorphism abstract super


    【解决方案1】:

    正如错误所说,您需要将一个 int 参数传递给构造函数中的 super()。

    public Name3(int cl,int tl)
        {
            super(cl);
            this.tl=tl;
        }
    

    【讨论】:

    • Name2 中添加所需的无参数构造函数也是一种选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-06
    • 2019-10-05
    • 2013-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多