Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

need help

 
ji soi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 41
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi ji soi

--> Variables,Static methods look for references
--> instances methods look for Instances
 
ji soi
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks i got it
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic