This site requires JavaScript, please enable it in your browser!
Greenfoot back
MRCampbell
MRCampbell wrote ...

2019/5/14

Parameters and Instance Variables.

MRCampbell MRCampbell

2019/5/14

#
I have seen others have differentiated between instance variables and parameters. Why don't we just use the same name?
1
2
3
4
5
6
public Creature(int speedP)
{
         speed = speedP;  // Please explain why I need to do this.
         drawCreatureImage();
         orientCreature();
}
danpost danpost

2019/5/14

#
The parameter has limited scope. It is similar to a local variable, in that is exists only for the duration of the execution of the method. Once the method is exited from (a return is executed or the end of the method is reached), the variable no longer exists. Your line 3 assigns the value of that variable to an instance field where its scope is less limited. It will exist for as long as that instance exists.
MRCampbell MRCampbell

2019/5/14

#
Thanks. That makes perfect sense. Is there documentation of standards on naming different type of variables? I added the "P" because this was a parameter.
danpost danpost

2019/5/14

#
MRCampbell wrote...
Is there documentation of standards on naming different type of variables?
Not really. It mostly is up to the programmer. Oftentimes, the same name as the field will be used as follows:
1
2
3
4
public Creature(int speed)
{
    this.speed = speed; // instance field = local variable
    // etc.
Other times, you might see an underscore being used:
1
2
3
4
public Creature(int speed_)
{
    speed = speed_;
    // etc.
If you were to add complete documentation and "publish" the class, you may be "forced" to specific naming so that the documentation makes sense and is easy to follow.
You need to login to post a reply.