public abstract class SuperClass {
public int x, y;
public int z = x + y;
}
SuperClass的每个子类都应具有x,y和z属性。但是,尽管x和y对于所有子类而言都可能不同,因此必须手动启动,但我如何才能聪明地启动z?即我不想z = x + y
在SuperClass的每个子类中调用。
我不想在SuperClass的每个子类中调用z = x + y。
只需在您的超类中提供za默认值即可,例如x + y,或者根据需要将其保留为空白。然后在子类中,根据需要在构造函数中定义z。
public class SuperClass{
int x, y, z;
SuperClass(int x, int y){
this.x = x;
this.y = y;
//pick a default value of z;
z = x + y;
}
}
public class Example extends SuperClass {
Example(int x, int y){
super(x , y);
//pick another z implementation here;
z = x * y ^ x;
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句