引用类型和对象类型

VWe*_*ber 13 java reference-type object-type

我正在指导同事OCA-Java 7认证.他也参加了一门课程并在那里做了准备考试.其中一个问题是关于参考和对象类型.这是代码:

package com.company;

public class Vehicle implements Mobile {

  public static void main(String[] args) {
    Truck theTruck = new Truck();
    Vehicle theVehicle = theTruck;
    Mobile theMobile = theVehicle;
  }
}

class Truck extends Vehicle {
}

interface Mobile {
}
Run Code Online (Sandbox Code Playgroud)

问题:什么是引用类型和对象类型theMobile

以下是选择:

  • 参考类型是"移动",对象类型是"移动"
  • B参考类型为"Truck",对象类型为"Truck"
  • C引用类型为"Mobile",对象类型为"Truck"
  • D参考类型为"Car",对象类型为"Mobile"

答案B被标记为正确答案......但是恕我直言答案C是对的.谁在这里错了?!

Sot*_*lis 8

我从未见过这些用于此的术语,但我认为它们的意思是声明类型与运行时类型.

Mobile theMobile = theVehicle;
Run Code Online (Sandbox Code Playgroud)

该变量具有声明的类型Mobile和运行时类型Truck.答案C是正确的.

术语引用类型是指Java中不是基元而不是null类型的任何类型.

  • 术语"引用类型"不仅仅指"编译时"类型.类型为"Mobile []"的变量可以保存对"Vehicle []"类型的单元素数组的引用,该数组又可以保存对"Truck"的引用.存储在数组中的引用类型将是"Vehicle",尽管在编译时已知的唯一类型是"Mobile". (2认同)

Not*_*bug 5

这里有什么不对?

你的书/材料中的印刷答案在这里是错误的:p

theMobile类型的引用变量Mobile是指类型的对象Truck.

所以答案3是正确的,引用类型是Mobile和Object类型Truck.

您可以检查theMobile.getClass()将返回的对象类型,Truck引用类型是代码中静态声明的内容,这Mobile在您的Mobile theMobile = ...声明中.