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

JAVA中的对象引用和类型转换,java,casting,object-reference,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. 在对数据进行类型转换之后,我

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

伪代码示例可以是:

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.
在对数据进行类型转换之后,我是否仍在处理相同的对象数据

对。强制转换将更改对对象的引用类型。它对对象本身没有任何影响

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

class MyClass extends VW // or extends something that extends 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);
    }
}
然后:


您是否试图同时使用JavaScript和Java小程序,并且需要从彼此访问对象?或者,您只是选择了错误的标签
javascript
,并且只想问一个Java问题吗?对不起,这不是javascript。这是Java,我会修正标记,
topSpeed
必须是可访问的,所以如果我最后调用
car.getTopSpeed()
,我会得到220?@FireFly3000:是的,如果
topSpeed
在代码中设置的地方确实可以访问。我使用getters/setters(最佳实践)添加了一个具体的示例。@T.J.Crowder如果我从代码中删除
d
,并启动
Base b=new b(1),您的示例为什么不起作用?它认为B不能转换为派生的d。@T.J.Crowder
B
将只是一个默认的
B
对象。
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