• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Variable shadowing

 
jack worthing
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,
can any body help me on this please

if Three has two distinct variables "i"
then how if

which 'i'( the 'i' in superclass Two or the immediate superclass Three) is printed
 
Himanshu Gupta
Ranch Hand
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i of class Three will get printed. The Object will use its instace variable. If you make Object of class Two and try to print its value of i then it will be 10.


Output


HTH
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The instance variable accessed will depend on the type of the reference and not the the actual object type.

for example...

Two t = new Two();
t.i gives 10

Two t = new Three();
t.i still gives 10

This is contrary to instance method behaviour.

Prompts me to wonder.. is there any use for this type of instance variable behaviour?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49817
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Gamini Sirisena:
. . . This is contrary to instance method behaviour.

. . . is there any use for this type of instance variable behaviour?


Instance methods are overridden; instance fields and static members are hidden. We have an FAQ about that.

The use of that type of behaviour is good for people who set exams, or want to make a point. You should probably avoid it like the plague in real-life code. Of course, if all your instance fields have private access, then you will never even know there is a problem with hiding.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49817
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
By the way, it's not called shadowing, but hiding.
 
Gamini Sirisena
Ranch Hand
Posts: 378
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agreed,
So wouldn't it be nice for the compiler to warn when the same identifier is used for instance variables across a class hierarchy?
 
Darryl Burke
Bartender
Posts: 5148
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Maybe it would be nice, but you shouldn't expect the compiler to do everything for you.

Most modern IDEs will give you a warning for this. It's usually an optional setting.
 
jack worthing
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thankyou
that was very informative
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic