我试图向上转换一个对象。但是在运行时对象类仍然是派生类。
Derived drv = new Derived();
Base base = (Base) drv;
System.out.println("Class : " + base.getClass());
//prints -> Class : class packagename.Derived
那么为什么类属性没有改变?
最佳答案
So Why class property didn't change?
因为 object 没有改变,只是你对它的引用的类型。转换对对象本身没有任何影响。
在 Java 中,与其他一些语言(谢天谢地)不同,引用的类型在很大程度上不会影响您获得的方法版本。例如,考虑这两个类(由 2rs2ts 提供——谢谢!):
class Base {
public Base() {}
public void foo() {
System.out.println("I'm the base!");
}
}
class Child extends Base {
public Child() {}
public void foo() {
System.out.println("I'm the child!");
}
}
这段代码:
Child x = new Child();
Base y = (Base) x;
y.foo();
...输出
I'm the child!
because even though the type of y
is Base
, the object that we're calling foo
on is a Child
, and so Child#foo
gets called. Here (again courtesy of 2rs2ts) is an example on ideone to play with.
The fact that we get Child#foo
despite going through a Base
reference is crucial to polymorphism.
Now, it just so happens that the method you were calling (getClass
) can only be Object#getClass
, because it's a final
method (subclasses cannot override it). But the concept is crucial and I figured it was probably the core of what you were asking about.
The chief thing that the type of the reference does is determine what aspects of an object you're allowed to access. For instance, suppose we add bar
to Child
:
class Child extends Base {
public Child() {}
public void foo() {
System.out.println("I'm the child!");
}
public void bar() {
System.out.println("I'm Child#bar");
}
}
这段代码无法编译:
Child x = new Child();
Base y = (Base) x;
y.bar(); // <=== Compilation error
...因为 Base
没有 bar
方法,所以我们不能通过类型引用访问对象的 bar
方法基础
。
关于java - 为什么 Java 对象类在转换后保持不变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22480192/