【发布时间】:2014-03-11 18:13:38
【问题描述】:
这里的一切都被重命名和简化了。
我有一个父类 (normalThing),其方法显示有关实例的一些数据,另一个类 (specialThing) 扩展父类以包含另一个实例变量 (addedPrice)。
我希望我的显示方法说明该实例是否为 specialThing,如果是,则显示 addedPrice。但是因为addedPrice只属于specialThing,我不知道怎么编码!
void displayInfo(){
StringBuilder d = new StringBuilder("Am I special? ");
if(this instanceof specialThing){
d.append("Yes, so I cost an extra " + this.addedPrice);
//No, I didn't expect that to work, but I had hope
}
else d.append("Nope.");
JOptionPane.showMessageDialog(null, d);
}
有没有什么方法可以做到这一点,而无需在 normalThing 类中创建一个“could-be-addedPrice”变量?
【问题讨论】:
-
不要让你的父类依赖子类。 从不。
-
@SotiriosDelimanolis 除了当它通过我信任的抽象(或覆盖)方法时!
-
@ElliottFrisch 依赖我的意思是专门在父源代码中使用子类型。使用
abstract方法,您不会这样做,所以没关系。
标签: java inheritance instance-variables extends instanceof