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?!
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.
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.
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