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

java, oop, orientation, polymorphism

Solution

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

Problem

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

Original source