[英]Class Hierarchy design for optional attribute
目前,我的应用程序具有以下类层次结构:
目前,“A类”具有称为“属性D”的属性,对于“B类”是强制性的,但在“C类”中是可选的。
我可以知道表示此数据结构的最佳方法吗? 这样,我们强制他们使用Class B和Class C引用该字段,而不是让其他人引用ClassA.getAttributeD而不检查它是否为NULL。
使用Attribute D
在Class B
添加构造函数。 在Class C
,只有这个属性的setter。
abstract class A {
Object attributeD;
void setAttributeD(Object attributeD) { this.attributeD = attributeD; }
Object getAttributeD() { return attributeD; }
}
class B extends A {
B(Object attributeD) { this.attributeD = attributeD; }
}
class C extends A {
}
不要过度使用继承。 通常它会使事情变得更加复杂。 您可以在问题中看到这一点。
看看这个:
Class A {
private int d = 1;
protected int getD() {
return d;
}
}
Class B extends A {
public void doStuff() {
B b = new B();
System.out.println(b.getD());
}
}
Class C extends A {
public void doStuff() {
C c = new C();
System.out.println(c.getD());
}
}
您的主要问题是避免用户访问attribute D
您可以通过将attribute D
设置为私有来执行此操作,然后声明受保护的方法以访问该属性。 这样,子类就能够访问该属性。
使A中的字段受到保护,或将其保密,并使其访问者受到保护。
因此,A类用户无法访问该字段,但B类和C类可以使用它,并且可以为其公开访问者。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.