如何在子类中正确调用超类的构造函数?

时间:2018-10-21 03:14:05

标签: java inheritance

我完全理解继承和super关键字的工作原理,但不是这种类型。

public class Stack<T> implements StackADT<T> {
    /**
     * The array into which the objects of the stack are stored.
     */
    private T[] data;
    /**
     * The number of objects in this stack.
     */
    private int size;
    /**
     * The default capacity of this stack.
     */
    private static final int MAX_SIZE = 100;
    /**
     * Constructs a new Stack with capacity for 100 objects
     */
    public Stack(){
        this.data = (T[]) new Object[MAX_SIZE];
        this.size = 0;
    }

    public Stack(int size){
        this.data = (T[]) new Object[size];
        this.size = 0;
    }

    public int getSize(){
        return this.size;
    }

我该如何在Stack的子类中调用此构造函数? 我需要将子类中的容量更改为52,并将其设置为discardPile。

我以前做过的例子就是这样

private double salary = 1500;

public Faculty(String n, String i, String o, double s) {
    super(n, i, o); //where names = n, i = ID, and o = office were inheriented from their parents' constructors which assigned name = n; and etc. 

    salary = s; //unique instance variable
}

这是一个更简单的示例,因为没有多个可使用的构造函数,并且将事物分配给字母。

我只想了解在这种情况下如何调用方法。

1 个答案:

答案 0 :(得分:1)

您需要的只是

public class discardPile<T> extends Stack<T> {
  discardPile() {
    super(52);
  }
}

将根据您提供的参数选择要调用的构造函数。