简体   繁体   English

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

[英]Object references and typecasting in JAVA

Do I still work on the same object data after a typecast of the data? 在对数据进行类型转换后,我仍在处理同一对象数据吗?

A pseudo code sample could be: 伪代码示例可能是:

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.

Do I still work on the same object data after a typecast of the data? 在对数据进行类型转换后,我仍在处理同一对象数据吗?

Yes. 是。 Casting changes the type of the reference you have to the object. 强制转换会更改您对对象的引用类型。 It has no effect on the object itself at all. 它对对象本身完全没有影响。

Note that in your example, for the cast to be successful, VW would have to be a superclass of MyClass or an interface MyClass implements, eg: 请注意,在您的示例中,要使转换成功, VW必须是MyClass的超类或MyClass实现的接口,例如:

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

or 要么

class MyClass implements VW

Concrete example: 具体示例:

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

Then: 然后:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM