• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Accessing overridden methods with supoerclss ref variable

 
Shaan patil
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HI,

We know that a superclass ref vaiable can access a overridden method.Then why is it that we canot access subclass instance vaiable from a superclass vaiable ??
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

The super keyword which allows one to access the superclass object [or maybe that part of the object which is inherited unchanged from the superclass] is directional. A subclass "knows" which superclass it inherits from. When you writeorthe subclass knows to look in Foo for its superclass implementation and in Bar Barbar and Barbarbar for its interfaces. Remember super always refers to what follows extends.

But there might be several classes which extend Foo, and several which implement Bar Barbar and Barbaranne. If you had a "sub" keyword, it would not "know" which subclass to look for. Even javadoc can only find "direct known subclasses" (look at non-final classes in the API specification and it says that quite often), not "all direct subclasses."

A subclass might also have additional fields which are not in the superclass; there is no way the superclass could "know about" them.

It would not work having a "sub" keyword. I hope I have explained why so you can understand it.

CR
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic