子对象在父类之间来回转换后是否会失去其独特的属性

2022-01-24 00:00:00 oop polymorphism orientation 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 对象丢失其成员变量?例如:

If I was to create an instance of Blackberry, cast it to a Phone object and then cast it back to Blackberry, would the original Blackberry object lose its member variables? E.g:

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.

Casting doesn't change the underlying object at all - it's just a message to the compiler that it can treat an A as a B.

如果A extends B 也不需要将A 强制转换为B,即不需要强制转换子类型到它的超类型;如果它是从超类型到子类型的,你只需要转换

It's also not necessary to cast an A to a B if A extends B, i.e. you don't need to cast a subtype to its supertype; you only need the cast if it's from a supertype to a subtype

相关文章