java – 在父类之间来回转换后,子对象是否会丢失其唯一属性

考虑以下类:

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();

解决方法:

转换根本不会改变底层对象 – 它只是向编译器发出的消息,它可以将A视为B.

如果A扩展B,也没有必要将A转换为B,即您不需要将子类型转换为其超类型;如果从超类型到子类型,你只需要演员表

上一篇:php – Laravel多态关系:将模型传递给控制器


下一篇:Java中的枚举和多态,扑克牌示例