为什么Java对象类在转换后仍保持不变? [英] Why Java object class remains same after casting?

查看:56
本文介绍了为什么Java对象类在转换后仍保持不变?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图up弃一个物体.但是在运行时,对象类仍保留为派生类.

I tried to upcast an objet. But at runtime object class is remained as a derived class.

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?

推荐答案

那为什么类的属性没有变化?

So Why class property didn't change?

因为对象没有改变,只是引用的类型.投射对对象本身完全没有影响.

Because the object hasn't changed, just the type of the reference you have to it. Casting has no effect at all on the object itself.

在Java中,与某些其他语言不同(值得庆幸的是),引用的类型在很大程度上不会影响您所使用的方法的版本.例如,考虑这两个类(由 2rs2ts  —谢谢!):

In Java, unlike some other languages (thankfully), the type of the reference largely doesn't affect which version of a method you get. For instance, consider these two classes (courtesy of 2rs2ts — thank you!):

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!

因为即使 y 的类型是 Base ,我们在其上调用 foo object Child ,因此调用 Child#foo .此处(同样由 2rs2ts 表示感谢)是

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.

尽管经过了 Base 引用,我们仍然得到了 Child#foo 的事实对于多态性至关重要.

The fact that we get Child#foo despite going through a Base reference is crucial to polymorphism.

现在,您正调用的方法( getClass )只能 成为 Object#getClass ,因为它是 final 方法(子类无法覆盖它).但是这个概念很关键,我认为这可能是您要问的核心.

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.

引用类型的主要作用是确定允许访问对象的哪些方面.例如,假设我们将 bar 添加到 Child :

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 方法基本.

...because Base has no bar method, and so we can't access the object's bar method through a reference with type Base.

这篇关于为什么Java对象类在转换后仍保持不变?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆