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?
A.
Reference type is Z; object type is Z.
B.
Reference type is Y; object type is Y.
C.
Reference type is Z; object type is Y.
D.
Reference type is X; object type is Z.
Explanation:
Note: Because Java handles objects and arrays by reference, classes and array types are known as reference types.
C
Explanation:
class Animal {
}
class Horse extends Animal {
}
public class Test {
public static void main(){
Animal a = new Horse();//mark1
}
}
look carefully the mark1
here we are declaring the reference variable a of type Animal
but actually we are creating the object of type Horse
so Object type is the type of object we create actually
and reference type is of the type that we use for referring
and in this case due to polymorphism we can also write as:
Animal a = new Animal();// both reference and object type are animal
Animal ah = new Horse();// reference type is Animal and object is Horse
Horse h = new Horse();// both reference and object type are Horse
The Answer is C.