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

Transfer methods between classes.

WeiJie Lim
Ranch Hand

Joined: Sep 05, 2012
Posts: 89


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

Joined: Jul 25, 2011
Posts: 41

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

Joined: Oct 13, 2005
Posts: 39815
    
  28
The reason it did not work is that the grammar requires all statements be inside methods (or constructors or initialisers).
Campbell Ritchie
Sheriff

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

Joined: Sep 05, 2012
Posts: 89
@ 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

Joined: Jul 25, 2011
Posts: 41

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

Joined: Jul 25, 2011
Posts: 41

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Transfer methods between classes.