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