The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
January 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Still confused ???

Posted by Kishori Sharan on January 22, 2001 at 1:14 PM

Hi SADDY
The mechanism that confused you is called name hiding. Since class A declares int i and B class also declares int i then class B doesn't inherit the int i of its super class A rather it hides the int i defined in its super class A. So if you just refer to i by its simple name in B then it will refer to i defined in B not in A. Second thing to remember is that if you refer to i as a.i or b.i then this expression refers to i which is determined by the type of object a or b not the actual reference that a or b contains. So
A a = new B ( ) ;
a.i ;
here a.i will always refer to i in class A because the declared type of a is class A. It another thing that a holds a refernce to an object of class B at run time. If you want to refer to i in class B thru a.i then you will have to write a code like
((B)a).i ;
NOte the two parentheses in above expression. You are first type casting a to type B ( you are safe to do it in your case ), so at compile time java knows that it has to refer to i from class A becaise ((B)a) is of type A. So if you change yuor line where you are printing i to
System.out.println(" i = "+ ((B)a).i);
then you will get what you are expecting.
So, in other words you can say that all field references like this a.i, b.i are resolved at compile time based on the type of a and b.

Thanx
Kishori



Replies:

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us