编译错误:A类中的构造函数A不能应用于给定类型

问题描述 投票:0回答:2

我想用构造函数初始化实例变量,但我得到一个编译错误。

class Test{


    public static void main(String[] args){

        A a = new A(5,6);
        System.out.println(a.i);
    }
}

class A{
    int i, k;
    A(int a, int b){
        this.i=a;
        this.k=b;   
    }
}

class B extends A{
    int k;
    B(int a, int b, int c){
        this.k = a;
    }
}

错误是:

Test.java:26: error: constructor A in class A cannot be applied to given types;
        B(int a, int b, int c){
                              ^
  required: int,int
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error
java inheritance constructor
2个回答
0
投票

好吧,你的问题是你不能构造一个对象B而不首先构造一个对象A.如果你在A中有一个默认构造函数,你就不需要在B中调用super(虽然它会被自动调用)。


3
投票

你错过了superB电话。您可以使用它来修复它

class B extends A{
    int k;
    B(int a, int b, int c){
        super(a,b);
        this.k = a;
    }
}

你也许打算使用this.k = c

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