Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 374
Eric T Avatar asked Dec 20 '12 14:12

Eric T


2 Answers

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.

like image 183
Sergey Kalinichenko Avatar answered Sep 19 '22 13:09

Sergey Kalinichenko


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

like image 28
Aviram Segal Avatar answered Sep 18 '22 13:09

Aviram Segal