简体   繁体   English

引用类型和对象类型更改Java

[英]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? myZ的引用类型是什么,它引用的对象的类型是什么?

A. Reference type is Z; A.参考类型是Z; object type is Z. 对象类型是Z.

B. Reference type is Y; B.参考类型是Y; object type is Y. 对象类型是Y.

C. Reference type is Z; C.参考类型是Z; object type is Y. 对象类型是Y.

D. Reference type is X; D.参考类型是X; object type is Z. 对象类型是Z.

In this situation, I know that the object type is for sure Y, because I can test it with the .getClass() method. 在这种情况下,我知道对象类型肯定是Y,因为我可以用.getClass()方法测试它。 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. 我假设它是Z,但这种假设是基于直觉而不是逻辑。

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. 因此,引用的类型是Z ,因此“C”应该是正确的答案。

The Object was created with new Y(); Object是用new Y();创建的new Y(); so the object type is Y 所以对象类型是Y

myZ was declared as Z ( Z myZ = ...; ) so the reference type is Z myZ声明为ZZ myZ = ...; ),因此引用类型为Z

Hence, the right answer is C 因此,正确答案是C.

The object is referenced to Z type 该对象引用Z类型

Z myZ = myX;

but originally it was created as Y type, 但最初它被创建为Y型,

Y myY = new Y();

Hence, ans is obviously C. 因此,ans显然是C.

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. 事实如他们所说,参考是Z型,对象类型是Y,所以C是正确的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM