Java 定义超类中私有子类成员的相同处理
我有一个家长班:Java 定义超类中私有子类成员的相同处理,java,inheritance,private,abstract,Java,Inheritance,Private,Abstract,我有一个家长班: abstract class Parent { abstract int getX(); } 以及两种不同的子类实现: class AgnosticChild extends Parent { private int x = 5; @Override int getX() { return x; } } class ManipulativeChild extends Parent { private static int x = 5;
abstract class Parent {
abstract int getX();
}
以及两种不同的子类实现:
class AgnosticChild extends Parent {
private int x = 5;
@Override
int getX() {
return x;
}
}
class ManipulativeChild extends Parent {
private static int x = 5;
ManipulativeChild() {
x++;
}
@Override
int getX() {
return x;
}
}
两种
getX()
实现都是相同的。有没有办法在保留x
的不同实现的同时消除这种冗余?假设getX()
实现在实践中要复杂得多。您可以将int变量拉到父类,并在那里实现getX
方法
abstract class Parent {
private int x;
public Parent(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
class AgnosticChild extends Parent {
public AgnosticChild() {
super(5);
}
}
class ManipulativeChild extends Parent {
ManipulativeChild() {
super(6);
}
}
更新:如果您想将
manipivechild
中的x
声明为非静态字段,则上面的代码片段仅等于您的代码。否则,这是两个不同的实现,无法按照建议的方式进行重构。您可以将int变量拉到父类,并在那里实现getX
方法
abstract class Parent {
private int x;
public Parent(int x) {
this.x = x;
}
public int getX() {
return x;
}
}
class AgnosticChild extends Parent {
public AgnosticChild() {
super(5);
}
}
class ManipulativeChild extends Parent {
ManipulativeChild() {
super(6);
}
}
更新:如果您想将
manipivechild
中的x
声明为非静态字段,则上面的代码片段仅等于您的代码。否则,这是两个不同的实现,无法按照建议的方式进行重构。不,这两个实现并不相同——一个访问静态字段,另一个访问实例字段。因此,尽管它们看起来一模一样,但在功能上却大不相同;在不改变类的行为的情况下,这里没有重用的机会。不,这两个实现是不同的——一个访问静态字段,另一个访问实例字段。因此,尽管它们看起来一模一样,但在功能上却大不相同;根据OP的代码,x在AgnosticChild
中是静态的,但在manufactivechild
-->中不是静态的,它不能是相同的x
,感谢您的更正。根据OP的代码,我在回答中添加了限制,x在不可知儿童
中是静态的,但在操纵儿童
-->中不是静态的,它不能是相同的x
,感谢您的更正。我在回答中增加了限制