Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

use of " this " ...

 
jay nair
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator





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 ]
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
jay nair
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks marc , understood,... this thread also helped ,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic