Why Java object class remains same after casting?

*爱你&永不变心* 提交于 2021-02-18 05:34:06

问题


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?


回答1:


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.

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!");
    }
}

This code:

Child x = new Child();
Base y = (Base) x;
y.foo();

...outputs

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");
    }
}

This code won't compile:

Child x = new Child();
Base y = (Base) x;
y.bar(); // <=== Compilation error

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




回答2:


You can not change the type of an instance in Java. All you're doing with your cast is reference it from a variable of a different type.




回答3:


An upcast does not change the object's type. As a matter of fact, NOTHING changes a Java object's type.

That's the very core of OO programming: An object has a defined behavior that can't be influenced from the outside.



来源:https://stackoverflow.com/questions/22480192/why-java-object-class-remains-same-after-casting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!