gpt4 book ai didi

java - 如何在java中使用父亲的方法和儿子的变量?

转载 作者:行者123 更新时间:2023-12-01 18:40:35 24 4
gpt4 key购买 nike

由于我的代码内容很长,我会尽量保持抽象。所以,我有一个抽象的父亲,包含适用于其所有儿子的方法。

abstract class a {
protected final void a_method() {
...do stuff
}
}

我还有另外两个类扩展了

class b extends a {
static int _int = 3;
}

还有,

class c extends a {
static int _int = 2;
}

如您所见,我所有的 b 始终具有相同的 static _int 变量,并且我所有的 c 也始终具有相同的 _int 变量。方法 a_method() 对于两个儿子来说都是完全相同的代码,只是使用了儿子的变量。我可以避免代码重复吗?因为我的变量是静态的,所以我无法在 a 中声明它,因为每个儿子的类需要不同(每个扩展类的内容不同)

最佳答案

更简单的方法是在类A中使用抽象方法返回子类的int值。

abstract class a {
protected final void a_method() {
int i = getValue();

...do stuff
}

protected abstract int getValue();

}

然后在你的子类中

class b extends a {
static int _int = 3;

protected int getValue() {
return _int;
}
}

关于java - 如何在java中使用父亲的方法和儿子的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20072133/

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