java - 为什么 Java 对象类在转换后保持不变?

标签 java class upcasting

我试图向上转换一个对象。但是在运行时对象类仍然是派生类。

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/

相关文章:

java - 如何创建由 gradle 预编译运行的注释处理器以将代码添加到方法中?

javascript - AngularJS:templateUrl 适用于 HTML 模板文件,但不适用于 .JSP

javascript - 我可以拥有与 javascript 中的类同名的对象吗?

javascript - 如何从另一个类调用 javascript 类并在数组中推送(追加)值?

java - Inheritance中关于NEW Keyword的打印顺序是怎样的?

java - 子类的对象不能调用自己的方法

java - @Formula 不能在 hibernate 状态下与对象一起工作

java - 使用递归来填充数组,而不实现方法重载?

c++ - 模板仅适用于内联定义

c++ - 使用模板将std::shared_ptr <Derived>上载到std::shared_ptr <Base>