gpt4 book ai didi

Java:将一个对象扩展到另一个对象

转载 作者:行者123 更新时间:2023-12-02 08:16:25 25 4
gpt4 key购买 nike

例如我有这个:

class A{
private int mine = 0; //Some field...
public A(int a){mine+=a; /*Some operation1...*/}
}


class B extends A{
private int mine = 0; //Some field...
public B(int a){mine-=a; /*Some operation2...*/}
}

我得到:

error: constructor A in class A cannot be applied to given types;
public B(int a){}
required: int
found: no arguments
reason: actual and formal argument lists differ in length
1 errors

我不明白这个错误?告诉我要做什么?

不过,如果“A”的构造函数没有参数,则代码可以工作。
但是我需要执行操作1(又名mine+=a;),所以我需要A的参数,但后来我失败了。

我被封闭在这个魔法圈里了。我该怎么办?

最佳答案

每个构造函数的第一条指令始终是调用其父类(super class)构造函数之一。如果您不明确执行此操作,编译器会为您插入此指令。构造函数

 public B(int a) {
mine-=a;
/*Some operation2...*/
}

因此相当于

public B(int a) {
super(); // invoke the no-arg super constructor
mine-=a;
/*Some operation2...*/
}

由于 A 没有无参数构造函数,因此编译失败。在这种情况下,您必须显式调用 super 构造函数之一:

public B(int a) {
super(a);
mine-=a;
/*Some operation2...*/
}

关于Java:将一个对象扩展到另一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10474701/

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