Lydia
Lydia

Reputation: 625

is super must called in order to use superclass' method for Java

class StackWithMin extends Stack<NodeWithMin>{

    public void push(int value){
        int newMin = Math.min(value, min());
        super.push(new NodeWithMin(value, newMin));
    }

    public int min(){
        if (this.isEmpty()){
            return Integer.MAX_VALUE;
        }else{
            return peek().min;
        }
    }
}

class NodeWithMin{
    public int value;
    public int min;
    public NodeWithMin(int v, int min){
        value=v;
        this.min=min;
    }
}

When I tested this class, it seems that without or with adding super. before push/peek(line 5 and line 12) produce the same result. Thus, is super necessary?

This author of this solution have super.push(), but didn't not prefix peek(), is there any reason she did that?

Upvotes: 0

Views: 295

Answers (1)

Jens
Jens

Reputation: 69440

superis only nessesary if StackWithMin overrides the push method and you will call the push method from Stack

Upvotes: 2

Related Questions