WhatACoder
WhatACoder

Reputation: 27

Why do I have to initialize the top at -1 two times in stacks?

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

Answers (2)

payloc91
payloc91

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

user207421
user207421

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:

  1. Initalize top inline, not in the constructor:

    int top = -1;
    
  2. Chain the constructors:

    public stack () { 
        this(MAX_ELEMENTS);
    }
    
    public stack (int elements) { 
        Array = new Object [elements]; 
        top = -1; 
    }
    
  3. Both.

when my program already stacked some elements?

No it didn't. It just created an array of the size you specified.

Upvotes: 1

Related Questions