Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes why a supertype ref variable can call the methods of Object class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "why a supertype ref variable can call the methods of Object class" Watch "why a supertype ref variable can call the methods of Object class" New topic
Author

why a supertype ref variable can call the methods of Object class

anagha desai
Greenhorn

Joined: May 08, 2008
Posts: 22
Hello ,
Here is an Ex :



Confused regarding why and how the compiler allows this - I know that all classes extend from Object class - but the interface doesnt right ?

So what gives .... ?

Thanks ,
-anagha
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39076
    
  23
Go and find the API documentation for class like ArrayList. You will see it extends AbstractList, extends AbstractCollection, extends Object, implements List, implements RandomAccess, implements Collection, implements Iterable, implements Serializable, implements Cloneable.

Some of those are direct, some indirect, so there is no double inheritance.

You can call a class by the name of its superclass or by the name of an interface it implements, directly or indirectly.

You can call an ArrayList an Object, AbstractCollection, AbstractList, List, Cloneable, Serializable, etc etc.

Of course if you declare your type as an Interface (not a good example: risk of confusion with the keyword interface), you can use such methods as are available in that particular interface. Similarly with a superclass; you use the methods available in the superclass you declare. An interface doesn't directly inherit from java.lang.Object, but when it becomes a class (implemented with the implements keyword) it implicitly becomes an Object as well, so all classes always have the Object methods.
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3603
    
  15
Any interface that doesn't have a super interface implicitly declares methods that match all the public methods of the Object class.

See the Java Language Specification section 9.2


Joanne
anagha desai
Greenhorn

Joined: May 08, 2008
Posts: 22
Thanks JOanne and Ritchie
This does help and clarify the doubt .

Its really nice on both of you to help out .



Thanks ,
-anagha

[ June 06, 2008: Message edited by: anagha desai ]
[ June 06, 2008: Message edited by: anagha desai ]
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39076
    
  23
You're welcome
 
GeeCON Prague 2014
 
subject: why a supertype ref variable can call the methods of Object class