子对象在父类之间来回转换后是否会失去其独特的属性 [英] Does a child object lose its unique properties after casting back and forth between a parent class

查看:47
本文介绍了子对象在父类之间来回转换后是否会失去其独特的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下类:

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

这篇关于子对象在父类之间来回转换后是否会失去其独特的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆