Maksim Dmitriev
Maksim Dmitriev

Reputation: 6209

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.

Upvotes: 2

Views: 50

Answers (3)

Shahid
Shahid

Reputation: 2330

No, you will always get true until you create a new GrandChild instance and comapre with it. Because both grandChild and grandChild2 is referencing same object.

public class A {

    static Parent parent;
    static GrandChild grandChild3;

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

        GrandChild grandChild = getGrandChild();
        GrandChild grandChild2 = getGrandChild();
        System.out.println(grandChild == grandChild2); // true
        System.out.println(grandChild == grandChild3); // false
    }

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

}

Note: If you want to check whether two object is referencing same object, use ==. But to check equality according to value, you have to use equals().

Upvotes: 1

shiri
shiri

Reputation: 745

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?

Upvotes: 1

Jesper
Jesper

Reputation: 206796

The method getGrandChild() always returns a reference to the same object; casting an object reference never creates a new object and never modifies an object or reference, so you will never see false with this code.

Casting is not some magical way to convert objects from one type to another. It's simply a mechanism to tell the compiler: I have a reference to a particular object here and you have to trust me that this is a GrandChild object, and don't give me any type errors. It's a way to get around the type checking that the compiler does.

You should avoid casting as much as possible, because it makes your code less type-safe.

Upvotes: 4

Related Questions