File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Shadowing and this.var Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Shadowing and this.var" Watch "Shadowing and this.var" New topic
Author

Shadowing and this.var

Gil Steidle
Ranch Hand

Joined: Nov 19, 2010
Posts: 30
An example like this is in the SCJP 6 study guide (pg 55) but doesn't give a clear enough explanation (for me at least) of what's going on. Why, in the setSize method, does the left hand side's "size" not refer to this.size implicitly? In the setSize2 method it does???

Just when I think that I am beginning to understand some of this java stuff, it goes horribly wrong.

Thanks,
Gil




The output:
C:\JAVA\SCJP\ch1>java VariableTester
1. Initial size = 9
2. setSize inbound arg = 1
3. setSize this.size = 9
4. setSize size = 1
5. Final size = 9

1a. Initial size = 9
2a. setSize2 inbound arg = 1
3a. setSize2 this.size = 1
4a. setSize2 size = 1
5a. Final size = 1

C:\JAVA\SCJP\ch1>
Vijitha Kumara
Bartender

Joined: Mar 24, 2008
Posts: 3860

Gil Steidle wrote:... Why, in the setSize method, does the left hand side's "size" not refer to this.size implicitly? In the setSize2 method it does??? ...

Because "setSize" method has a local variable called "size" which shadows the instance variable "size" whereas in "setSize2" method "size" resolves to the instance variable. And remember in the first case both side refers to the same (local) "size" variable. It's the scope what matters, it uses the nearest scope.


SCJP 5 | SCWCD 5
[How to ask questions] [Twitter]
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3649
    
  17

There's no difference between a left-hand and a right-hand operand in terms of what variable is being referred to. in setSize, 'size' refers to the method parameter. If you want to reference the instance variable 'size', you will have to refer to it explicitly by using this.size. You don't have to do this in setSize2 because the instance variable isn't being shadowed by the method parameter.
Gil Steidle
Ranch Hand

Joined: Nov 19, 2010
Posts: 30
Ah, makes sense now, thanks for the explanations!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Shadowing and this.var