子对象在父类之间来回转换后是否会丢失其唯一属性
2022-09-03 09:16:40
请考虑以下类:
public class Phone {
private boolean has3g;
public boolean has3g() {
return has3g;
}
public void setHas3g(boolean newVal) {
has3g = newVal;
}
}
public class Blackberry extends Phone {
private boolean hasKeyboard;
public boolean hasKeyboard() {
return hasKeyboard;
}
public void setHasKeyboard(boolean newVal) {
hasKeyboard = newVal;
}
}
如果我要创建 一个实例,将其强制转换为一个对象,然后将其转换回 ,原始对象是否会丢失其成员变量?例如:Blackberry
Phone
Blackberry
Blackberry
Blackbery blackbery = new Blackberry();
blackbery.setHasKeyboard(true);
Phone phone = (Phone)blackbery;
Blackberry blackberry2 = (Blackberry)phone;
// would blackberry2 still contain its original hasKeyboard value?
boolean hasKeyBoard = blackberry2.hasKeyboard();