Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Transfer methods between classes.

 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


In this sample example, why can't I just run foo.doFoo(); without the doSomething method enclosing it ?

Also, I am not too clear about this.foo = foo . What does it actually mean ? It calls the foo variable which refers to the Foo Object and then sets it to foo again ? :O

Guidance is fully appreciated
 
Jj Hill
Ranch Hand
Posts: 41
Chrome Java Netbeans IDE
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I haven't looked through why doFoo() doesn't work yet but I'll get to that.

is a matter of scope. http://www.java-made-easy.com/variable-scope.html
Basically, in class Bar there are two variables named "foo" - the one in the parameter of the constructor ("public bar(Foo foo)") and the class field - "private Foo foo"
The code sets the class field foo to the parameter foo, because otherwise you would just be setting foo equal to itself (parameter foo takes priority over class field foo).
tl;dr this.foo refers to class fields, and foo refers to local variables when applicable.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The reason it did not work is that the grammar requires all statements be inside methods (or constructors or initialisers).
 
Campbell Ritchie
Sheriff
Pie
Posts: 49466
64
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are correct about shadowing, but not to call it a class field. It is an instance field. You only call fields class fields if they are static.
 
WeiJie Lim
Ranch Hand
Posts: 92
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@ Jj Hill :
Hmm so this.foo = foo; essentially makes the instance variable foo to be equal to the local variable foo right ?

@ Campbell Ritchie :

Oh foo.doFoo(); is considered a statement ? Didn't know that. My java fundamentals are weak =/

So calling doFoo(); by itself is considered a statement too and it is supposed to be in a method ?
 
Jj Hill
Ranch Hand
Posts: 41
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Campbell Ritchie wrote:You are correct about shadowing, but not to call it a class field. It is an instance field. You only call fields class fields if they are static.

Ok thanks, I didn't know that.
 
Jj Hill
Ranch Hand
Posts: 41
Chrome Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
WeiJie Lim wrote:@ Jj Hill :
Hmm so this.foo = foo; essentially makes the instance variable foo to be equal to the local variable foo right ?

Yes.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic