• Post Reply Bookmark Topic Watch Topic
  • New Topic

using this in constructor  RSS feed

 
shivang sarawagi
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Can anyone tell the point of writing within the constructor
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
shivang sarawagi wrote:Can anyone tell the point of writing within the constructor

Yes, the compiler has two fields called 'factory' to deal with, so you need to indicate specifically which one you want it to use. By default it uses the one defined closest to the code (the parameter), so you need the this keyword to tell it that you mean the one defined for the instance.

Winston
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what it is doing is assigning the SimplePizzaFactory that was passed to it in the constructor to the member variable called factory. this is quite a common thing to do.
 
dennis deems
Ranch Hand
Posts: 808
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In other words, a parameter, whether for a method or a constructor, defines a variable with local scope. And if it so happens that this local variable is given the same name as an instance field, then the instance field is shadowed. Within the scope of the PizzaShop constructor, "factory" means the argument and not the instance field. So if we just wrote "factory=factory", we would merely be re-assigning to the local argument variable the value it already had, and the instance field would not be initialized.
 
Mohamed Sanaulla
Bartender
Posts: 3185
34
Google App Engine Java Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There was a similar discussion here regarding the use of "this" keyword.
I think you should try to run the program without the "this" in the constructor and see the difference.
 
Randall Twede
Ranch Hand
Posts: 4696
8
Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dennis, that is the best explanation i have ever heard.
 
dennis deems
Ranch Hand
Posts: 808
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Randall Twede wrote:Dennis, that is the best explanation i have ever heard.


Thank you!
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!