wood burning stoves 2.0*
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


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
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: 3816

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: 3574
    
  14

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!
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Shadowing and this.var
 
Similar Threads
Java-4a Please
Cattle Drive- Assignment 4a
K&B SCJP 1.6 book -> "collections" : error in code ?
Why is assigning "size" that way considered WRONG?
Traps to be aware of in any SCJP test !!!!! :)