Does a child object lose its unique properties after casting back and forth between a parent class

被刻印的时光 ゝ 提交于 2019-12-18 12:56:14

问题


Consider the following classes:

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;
    }
}

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

回答1:


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.

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




回答2:


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?

You have instantiated a Blackberry. This will remain a Blackberry until the it is GCed.
When you cast it to Phone you are not changing the fact that the type is Blackberry. You are just treating it as a Phone i.e. you have only access to its generic properties (that of Phone).
The extended properties of Blackberry are no longer visible despite the fact that the concrete instance is still a Blackberry and you can successfully cast it back to access the Blackberry properties.



来源:https://stackoverflow.com/questions/16224277/does-a-child-object-lose-its-unique-properties-after-casting-back-and-forth-betw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!