aspose file tools*
The moose likes Beginning Java and the fly likes Variable shadowing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Variable shadowing" Watch "Variable shadowing" New topic
Author

Variable shadowing

jack worthing
Greenhorn

Joined: Dec 02, 2008
Posts: 18
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

Joined: Aug 18, 2008
Posts: 598

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


My Blog SCJP 5 SCWCD 5
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 350
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

Joined: Oct 13, 2005
Posts: 39436
    
  28
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

Joined: Oct 13, 2005
Posts: 39436
    
  28
By the way, it's not called shadowing, but hiding.
Gamini Sirisena
Ranch Hand

Joined: Aug 05, 2008
Posts: 350
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

Joined: May 03, 2008
Posts: 4642
    
    5

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.


luck, db
There are no new questions, but there may be new answers.
jack worthing
Greenhorn

Joined: Dec 02, 2008
Posts: 18
thankyou
that was very informative
 
 
subject: Variable shadowing