10

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.

1
  • I would go with C, the object was create with new Y(); and myZ is declared as Z Commented Dec 20, 2012 at 14:07

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

what is the meaning of reference type overall? Why do we need it?
The reference declares the interface of the object. if type X had methods getA(), getB() and getC(). And type Y only has getA() and getB(), then by changing the interface (reference type) from X to Y, you could only get access to getA() and getB() even though the object is of type X.
2

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

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.