Author Topic:   Marcus Exam#2 Q50
Howard Stern
ranch hand
posted March 30, 2000 10:31 PM             
Given the folowing classes which of the following will compile without error?


interface IFace{}
class CFace implements IFace{}
class Base{}

public class ObRef extends Base{
public static void main(String argv[]){
ObRef ob = new ObRef();
Base b = new Base();
Object o1 = new Object();
IFace o2 = new CFace();
}
}

1)o1=o2;
2)b=ob;
3)ob=b;
4)o1=b;

The answer is 1), 2) and 4).
However in case of 1) I would assume that the compiler shall give a casting error since an interface does not belong to the Object class hierarchy.
Anybody that can throw some light on this?

Paul Wheaton
sheriff
posted March 31, 2000 06:29 AM             
I think I would be suspicious too. Have your tried running it through the compiler?

maha anna
bartender
posted March 31, 2000 08:28 AM             
Howard,
All objects of Types class/interface/arrays CAN BE ASSIGNED to a ref of type Object class ,without any casting. The compiler will not complain. Because all objects of any of the above mentioned types desend from Object class.
So the given answer is correct for compile time and run time
regds
maha anna

[This message has been edited by maha anna (edited March 31, 2000).]

Arya
unregistered
posted March 31, 2000 10:03 AM           
To add to what Maha said : An object can be refenced by a variable that is of a superclass type,as the child class inherits all the elements(except private) of the base class.

Howard Stern
ranch hand
posted March 31, 2000 10:20 AM             
Thanks to Paul, Maha and Arya. My doubt arose since we are assigning a varaible reference (not the object) of type interface to a variable of type Object. I had figured that since an interface does not descend from Object unlike classes you cannot cast it implicitly. However I referred to the JLS and found out that a variable T of type interface can be implicitly cast to a variable S of type Object.

|