Maksim Dmitriev Maksim Dmitriev - 3 months ago 7
Java Question

Is it possible that Java returns a reference to another variable after applying the cast operator?

I have got three classes.

Parent

package sample;

public class Parent {

}


Child

package sample;

public class Child extends Parent {

}


GrandChild

package sample;

public class GrandChild extends Child {

}


And I run the following code:

package sample;

public class Main {

static Parent parent;

public static void main(String[] args) {
parent = new GrandChild();

GrandChild grandChild = getGrandChild();
GrandChild grandChild2 = getGrandChild();
System.out.println(grandChild == grandChild2);
}

private static GrandChild getGrandChild() {
return (GrandChild) parent;
}

}


Is it possible to see
false
in the console? I always see true.

Answer

Casting doesn't change the object being pointed to.

However, you should not be relying on the == operator in your code to compare between two objects (use equals() instead).

Is there a particular reason why you need this to work? Or just curiosity?