| Author |
need help
|
ji soi
Greenhorn
Joined: Jun 14, 2005
Posts: 13
|
|
class Super { int index = 5; public void printVal() { System.out.println( "Super" ); } } class Sub extends Super { int index = 2; public void printVal() { System.out.println( "Sub" ); } } public class runner { public static void main( String argv[] ) { Super sup = new Sub(); System.out.print( sup.index + "," ); sup.printVal(); } } The output is 5 and sub. I thought its 2 and sub. Super class ref. sup -> sub class obj. sup.printval() calling sub class method & printing "sub". Iam clear abt that. sup.index() : If its the same case sup will call sub class index var. Don't they? . Then why its 5 Not 2. plz help me with this/ thanks
|
 |
Shivakanth Thyagarajan
Ranch Hand
Joined: Mar 28, 2005
Posts: 41
|
|
Hi Joi, The concept of overriding is limited to the instance methods, it is not extended to instance variables. The instance variables are resolved at compile time. In the above example the answer is 5 and sub since you are printing the index value of the super class version which is accessible since the access control for index variable is default. Super a = new Sub( ) ; a.index ---- > will point to the value of the index variable belonging to the Super class. Thanks Shiva
|
 |
vidya sagar
Ranch Hand
Joined: Mar 02, 2005
Posts: 580
|
|
hi ji soi --> Variables,Static methods look for references --> instances methods look for Instances
|
 |
ji soi
Greenhorn
Joined: Jun 14, 2005
Posts: 13
|
|
|
Thanks i got it
|
 |
 |
|
|
subject: need help
|
|
|