JAVA中的对象引用和类型转换

时间:2015-11-09 09:05:43

标签: java casting object-reference

在对数据进行类型转换后,我是否还在处理相同的对象数据?

伪代码示例可以是:

MyClass car = new MyClass();
car.setColor(BLUE);

VW vw = (VW)car; //Expecting to get a blue VW.
vw.topSpeed = 220;

//Will car have the top speed set now? If topSpeed is a part of the Car object.

1 个答案:

答案 0 :(得分:2)

  

在对数据进行类型转换后,我是否还在处理相同的对象数据?

是。强制转换会更改对象的引用类型。它根本不会影响对象本身。

请注意,在您的示例中,为了使转换成功,VW必须是MyClass或接口MyClass实现的超类,例如:

class MyClass extends VW // or extends something that extends VW

class MyClass implements VW

具体例子:

class Base {
    private int value;

    Base(int v) {
        this.value = v;
    }

    public int getValue() {
        return this.value;
    }

    public void setValue(int v) {
        this.value = v;
    }
}

class Derived extends Base {
    Derived(int v) {
        super(v);
    }
}

然后:

Derived d = new Derived(1);
System.out.println(d.getValue());  // 1
Base b = d;                        // We don't need an explicit cast
b.setValue(2);                     // Set the value via `b`
System.out.println(d.getValue());  // 2 -- note we're getting via `d`
Derived d2 = (Derived)b;           // Explicit cast since we're going more specific;
                                   // would fail if `b` didn't refer to a Derived
                                   // instance (or an instance of something
                                   // deriving (extending) Derived)
d2.setValue(3);
System.out.println(d.getValue());  // 3 it's the same object
System.out.println(b.getValue());  // 3 we're just getting the value from
System.out.println(d2.getValue()); // 3 differently-typed references to it