JAVA 中的对象引用和类型转换
Object references and typecasting in JAVA
在对数据进行类型转换后,我是否仍在处理相同的对象数据?
伪代码示例可以是:
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?
是的。强制转换会更改您对对象的引用类型。它对对象本身完全没有影响。
请注意,在您的示例中,要使转换成功,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
在对数据进行类型转换后,我是否仍在处理相同的对象数据?
伪代码示例可以是:
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?
是的。强制转换会更改您对对象的引用类型。它对对象本身完全没有影响。
请注意,在您的示例中,要使转换成功,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