• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Liutauras Vilda
  • Paul Clapham
Sheriffs:
  • paul wheaton
  • Tim Cooke
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Piet Souris
Bartenders:
  • Mike London

need help

 
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 41
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks i got it
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic