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

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

问题描述

考虑以下类:

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

如果我要创建一个<$ c的实例$ c> Blackberry ,将其投放到电话对象,然后将其强制转换为 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();


推荐答案

Casting根本不会改变底层对象 - 它只是向编译器发出的消息,它可以将 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.

如果<$ c $,也没有必要将 A 转换为 B c> 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天全站免登陆