dotslash dotslash - 1 year ago 69
Java Question

getClass() returns derived class name after upcasting

I've come across a weird thing while learning Java. Consider the following program:

public class GetClassNameInheritance {
public static void main(String[] args) {
Employee e = new Employee();
Person p = (Person) e;

class Person {


class Employee extends Person {


I was expecting the output to be
because of the cast, but it is
! Honestly, I'm stumped and can't find an explanation. The official Oracle tutorial doesn't mention this behavior, and the docs seem too terse to be helpful. I can make out from other StackOverflow examples that this is something to do with "runtime class" but I don't understand the underlying idea. Can someone explain what's going on here?

Answer Source

In Java, Type casting does not change the type of object. Once an Employee, your object is always an Employee. Type casts do not work like in other languages such as C/C++.

Though the p reference is of type Person, it is in fact referring to an object of type Employee in the JVM heap. When you invoke the p.getClass() method, the reference in turn invokes the method on the object and not on the reference. That's the reason you see Employee in your output.

The only type of casts that would work is the one that you can perform on primitives.

int x = (int)2.5f;

The return value will be type cast to int.

You can read more about type casts and conversions here:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download