Link to home
Start Free TrialLog in
Avatar of yattias
yattias

asked on

Comparable interface

Does the Object class implement the Comparable interface?  I now know that it is necessary to type cast an object to Comparable to insure the compiler that the object has a compareTo method.  What if the object does not implement Comparable interface, would type casting it in the following way (Comparable)obj will make it implement the comparable interface? what actually happens when you type cast an object to Comparable?

thanks
Avatar of gauravkrtomar
gauravkrtomar

No the Object class does not implements the Comparable interface. If you typecast an object which is not implemeting the interface then you will get a runtime exception- ClassCastException. type casting it in the following way (Comparable)obj will not implement the interface.
Avatar of yattias

ASKER

so it will only ensure the compiler that the object implements the Comparable interface?
ASKER CERTIFIED SOLUTION
Avatar of gauravkrtomar
gauravkrtomar

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Mayank S
>> so it will only ensure the compiler that the object implements the Comparable interface?

No it will also take care of the comparision on run-time.
Avatar of yattias

ASKER

I sort of get it, but could you explain me this line Parent parentChild = new Child(); because you are declaring a Parent object but using the child() constructor and I am not so sure why
Because a super-class reference can hold a sub-class object. Like an Object reference can refer to an object of any class (because it is at the root of the hierarchy).
>> public class Child extend Parent implements A{

make that *extends*
Using interfaces increases the abstract nature of the code:-
U must be knowing that ArrayList and Vector both implements the List interface so in your code u can do
List list=new ArrayList();
or
List list=new Vector();

then in your program you need not worry about how the list is implemented, u r just getting the refernce as List and can perform the list functions.