javareference-typeobject-type

Reference type and object type


I'm mentoring a colleagues OCA-Java 7 Certification. He's also attending a course and did a preparation exam there. One of the questions was about reference and object types. Here is the code:

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 {
}

The question: What is is the reference type and the object type of theMobile?

And here are the choices:

Answer B is marked as the correct answer...but IMHO answer C is right. Who's wrong here?!


Solution

  • Whats wrong here ?

    Printed answer in your book/material is wrong here :p

    Reference variable theMobile of type Mobile is referring to object of type Truck.

    So answer 3 is correct, Reference type is Mobile and Object type is Truck.

    You can check object type with theMobile.getClass() which will return Truck and reference type is what statically declared in your code, which is Mobile in your Mobile theMobile = ... declaration.