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.print
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
.