• Post Reply Bookmark Topic Watch Topic
  • New Topic

Classes and Constructor  RSS feed

 
Sam Pauken
Ranch Hand
Posts: 84
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For the two sets of code below for my constructor, is there any inherent difference between them? When would you use one as opposed to the other?





Also, could I do?

Is one better than the other?
 
Ulf Dittmer
Rancher
Posts: 42972
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
They accomplish the same. Line 4 in both is superfluous. Line 2 in the third snippet accomplished nothing, as the price variable is not used after its value is assigned to priceEach.
 
Nick Fio
Greenhorn
Posts: 7
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Sam! This is my first attempt at helping someone else here ... EVER!

You understand that a constructor constructs an object using the stuff inside of the curley braces as the blueprint. And you understand that a constructor can be used to construct one object, two objects, or a gazillion objects.

You've got to keep in mind that all of that stuff about the scope of a variable that applies to methods and loops ... it also applies to constructors!

The keyword this means that you want this stuff to apply to this instance of this object.

Suppose that you had instance variables (aka, fields) named gameName and priceEach, and that your constructor parameters were also had the same names. Code like this ...



... would NOT end up assigning what was passed into the constructor to the object's fields. Scope!

But if you use this ...



... the the Java compiler says, "Ohhhhh ... dude wants to create a Game object whose fields are these values!"

Your first example is fine. An alternative to it is using the keyword this like I did previously, which has the advantage of you not having to create new names and to mentally remember that these names refer to same thing. It's a pretty nice feature when you get to writing more and more complicated programs and don't want to keep racking your brains for new and creative names for the same thing!

Your second example is kind of redundant because the compiler can figure out that you want name to be assigned to gameName and price to be assigned to priceEach without this.

Hang in there. this gave me fits when I first studied it.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!