Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • A Reference type is "Mobile", object type is "Mobile"
  • B Reference type is "Truck", object type is "Truck"
  • C Reference type is "Mobile", object type is "Truck"
  • D Reference type is "Car", object type is "Mobile"

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

like image 722
VWeber Avatar asked May 27 '14 14:05

VWeber


2 Answers

I've never seen those terms used for this, but I assume they mean declared type vs run time type.

Mobile theMobile = theVehicle;

The variable has a declared type of Mobile and a run time type of Truck. Answer C is correct.

The terms reference type refer to any type in Java that is not a primitive and not the null type.

like image 61
Sotirios Delimanolis Avatar answered Oct 14 '22 19:10

Sotirios Delimanolis


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.

like image 33
Not a bug Avatar answered Oct 14 '22 19:10

Not a bug