Reputation: 45
I'm stuck on a homework question which asks me to define a constructor for class Jar which initialises the variable position to 0 and the variable stone to null. Was just wondering if the code I did below is the right way to do this? Also am I able to initialise the values used in this constructor in a different class?
public class Jar
{
public int position;
public Jar stone;
public Jar()
{
position = 0;
stone = null;
}
}
Upvotes: 0
Views: 51
Reputation: 1074098
Was just wondering if the code I did below is the right way to do this?
Yes, although:
As Stultuske points out, those are the default values that the fields will get even if you don't assign anything to them, so the constructor isn't necessary. But if the assignment said to write one...
I always advise being explicit:
this.position = 0;
this.stone = null;
Java allows you to leave off the this.
part, but I wouldn't.
Upvotes: 2