File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes need help Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "need help" Watch "need help" New topic

need help

ji soi

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 + "," );

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/

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

Joined: Jun 14, 2005
Posts: 13
Thanks i got it
I agree. Here's the link:
subject: need help
jQuery in Action, 3rd edition