I know you guys hate helping with homework, but I thought I might ask anyways…
So, I have the question:
Describe two ways in which an instance variable can be initialized when an object is constructed.
Now, the first way would obviously be to assign the instance variable to a formal parameter of the constructor:
public class Example {
private int valueOne;
public Example(int val1) {
valueOne = val1;
}
}
However, I still need another way.
One possibility could be to simply assign the instance variable in the constructor to a value not accepted as a parameter of the constructor:
public class Example {
private int valueTwo;
public Example() {
valueTwo = 2;
}
}
But that just seems like a cheap solution to the problem that isn’t that different from the first solution.
So, I was wondering about something like this:
public class Example {
private int valueOne = 1;
}
However, I was wondering if that still assigns the valueOne the value 1 at the time of the object’s construction, or does something different?
And, if it does do something different, what would be another alternative to the problem? Is there something else I’m missing?
Your two ways are the two ways I would have thought about.
The latter initializes the value when the object is constructed. It actually happens even before the constructor runs (you can test that):
This prints: