在某些调用方知道其值而某些调用方不知道的情况下,处理空白最终变量的最佳方法是什么?
在下面的场景中,我应该创建一个新的子类来实例化c2吗?
class Parent {
private int p1;
private int p2;
}
class Child1 extends Parent {
private final int c1;
//want to add a final variable c2 here but cannot add since one of the callers do not the know the value of c2;
public Child1(int c1){
this.c1 = c1;
}
}
class Service {
public void createChild(int c1){
Child c1 = new Child1(c1);
//business logic
}
}
class ServiceCall1 {
createChild(10);
// I do not know the value of c2 here
}
class ServiceCall2 {
createChild(20);
//I know the value of c2 here
}
这个问题不是很清楚。你能出示一些代码吗?
但总的来说,我认为类继承是由实体的关系驱动的。
例如,父类Person
有一个子类Student
。众所周知,斯图登是一个人,所以这种结构是一个很好的选择
另一个子类Teacher
,它应该继承自Person
,而不是Student
。因为在学校里,一个既是学生又是老师的人是非常非常罕见的
因此,如果类Teacher
继承自Student
,这很奇怪,不是一个好的选择。
我认为blank final variable
是语言层面的东西
我建议不要让类继承依赖于那些东西。