File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Shadowing and this.var

 
Gil Steidle
Ranch Hand
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3908
9
Chrome Fedora Hibernate
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 4846
34
Chrome Netbeans IDE Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 30
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ah, makes sense now, thanks for the explanations!
 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic