Maksim Dmitriev Maksim Dmitriev - 4 months ago 13
Java Question

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

I have got three classes.


package sample;

public class Parent {



package sample;

public class Child extends Parent {



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
in the console? I always see true.


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?