File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes use of Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Customer Requirements for Developers this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "use of " this " ..." Watch "use of " this " ..." New topic

use of " this " ...

jay nair

Joined: Sep 13, 2005
Posts: 28

are'nt we supposed to declare another variable " ounces " inside the Constructor ?? , n if its the " private int ounces " then is it not supposed to be declared before this Constructor ???

am i missing something too obvious ? help will be appreciated , thanks

EDIT by mw: Put long code comment inside /* ... */ tags with line breaks to avoid a really long line that won't break within code tags.
[ April 22, 2006: Message edited by: marc weber ]

Preparing for SCJP 5
marc weber

Joined: Aug 31, 2004
Posts: 11343

Parameters passed to methods/constructors are copies assigned to variables that are local to the method/constructor. So you might think of the local declaration being implicit in the argument list.

As a variable name for a parameter, "ounces" is local to the constructor. Using "this" to reference the calling instance allows access to the instance variable "ounces." So this.ounces = ounces; assigns the local variable's reference to the instance variable.

The order of the instance declaration relative to the constructor doesn't matter because instance variables are initialized prior to the constructor body executing.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
jay nair

Joined: Sep 13, 2005
Posts: 28
So when you say this.ounces = ounces , it acatully means that private int ounces = int ounces ( declared in the arg of the contructor) ?
jay nair

Joined: Sep 13, 2005
Posts: 28
thanks marc , understood,... this thread also helped ,
I agree. Here's the link:
subject: use of " this " ...
It's not a secret anymore!