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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With