Reputation: 27
I am currently studying stacks and there is one thing that I do not understand. I have to create two constructors. What I don't understand is why do I have to set the top at -1 for my second constructor when my program already stacked some elements? Thanks
public stack () {
Array = new Object [MAX_ELEMENTS];
top = -1;
}
public stack (int elements) {
Array = new Object [elements];
top = -1;
}
Upvotes: 1
Views: 81
Reputation: 3809
Additionally to the other answer, you can also use an instance initializer:
{
top = -1;
}
It will be called regardless of the constructor user.
Upvotes: 0
Reputation: 310957
why do I have to set the top at -1 for my second constructor
You don't, in general, but you do in this case because there are two separate constructors that don't call each other. There are several better solutions:
Initalize top
inline, not in the constructor:
int top = -1;
Chain the constructors:
public stack () {
this(MAX_ELEMENTS);
}
public stack (int elements) {
Array = new Object [elements];
top = -1;
}
Both.
when my program already stacked some elements?
No it didn't. It just created an array of the size you specified.
Upvotes: 1