Eric T
Eric T

Reputation: 946

Reference Type and Object Type Changing Java

Given:

public class X implements Z {

    public String toString() { return "I am X"; }

    public static void main(String[] args) {
        Y myY = new Y();
        X myX = myY;
        Z myZ = myX;
        System.out.println(myZ);
    }
}

class Y extends X {

    public String toString() { return "I am Y"; }
}

interface Z {}

What is the reference type of myZ and what is the type of the object it references?

A. Reference type is Z; object type is Z.

B. Reference type is Y; object type is Y.

C. Reference type is Z; object type is Y.

D. Reference type is X; object type is Z.

In this situation, I know that the object type is for sure Y, because I can test it with the .getClass() method. But I'm unsure of how to check what the reference type is. I'm assuming it is Z but that assumption is based on gut feeling and not logic.

Can anyone elaborate on what the reference type might be and why?

Thank you.

Upvotes: 10

Views: 3710

Answers (4)

thedarkside ofthemoon
thedarkside ofthemoon

Reputation: 2291

I know it is confusing because of the wrong answer that is marked as the true one; I have also met it. The truth is as they say, the reference is of type Z and the object type is Y, so C is the correct answer.

Upvotes: 0

0x6900
0x6900

Reputation: 155

The object is referenced to Z type

Z myZ = myX;

but originally it was created as Y type,

Y myY = new Y();

Hence, ans is obviously C.

Upvotes: 0

Aviram Segal
Aviram Segal

Reputation: 11120

The Object was created with new Y(); so the object type is Y

myZ was declared as Z (Z myZ = ...;) so the reference type is Z

Hence, the right answer is C

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726987

The type of the object reference is defined statically at the point of its declaration:

Z myZ = ...

Therefore, the type of the reference is Z, so "C" should be the right answer.

Upvotes: 5

Related Questions