抽象类&构造函数

时间:2016-09-29 07:36:50

标签: java constructor abstract

如果我有abstract class名为员工constructor

public abstract class Employee {
    //instance fields or attributes of employee
    public Employee(String name, String extensionNumber){
       //initializing the variables
    }       

如何撰写constructor subclass名为 SalariedEmployee attribute还有super class(不在 for(i=0;i<6;i++){ countByActivties.getKeys(function(d){ return d.key;});//there is no getKeys function in an array. } )?

4 个答案:

答案 0 :(得分:7)

您只需编写一个能够为超类构造函数提供nameextensionNumber值的构造函数,并执行您喜欢的任何其他操作。

我个人也会制作Employee构造函数protected,因为它实际上只有 才能用于子类。请注意,除了这方面,在抽象类和具体类中使用构造函数之间确实没有区别。

public abstract class Employee {
    // ...
    protected Employee(String name, String extensionNumber) {
        // ...
    }
}

public class SalariedEmployee extends Employee {
    // ... (probably a field for the salary)

    public SalariedEmployee(String name, String extensionNumber, BigDecimal salary) {
        // Pass information to the superclass constructor to use as normal
        super(name, extensionNumber);
        // Use salary here
    }
}

请注意, ,只要您可以在super调用中提供参数,就可以使参数与超类的参数相匹配。例如:

public class SalariedEmployee extends Employee {
    ...

    public SalariedEmployee(Employee plainEmployee, BigDecimal salary) {
        super(plainEmployee.getName(), plainEmployee.getExtensionNumber());
        // Use salary here
    }
}

(您可能还需要考虑将extensionNumber设为int而不是String,因为它实际上可能是一个简单的数字 - 而完整的电话号码最好存储为字符串。)

答案 1 :(得分:3)

您可以写下以下内容:

public SalariedEmployee(String name, int extensionNumber, BigDecimal salary) {
    super(name, extensionNumber);
    this.salary = salary;
}

构造函数可以作为第一行,使用class或使用this(args)的超类构造函数调用同一super(args)的另一个构造函数。如果没有进行此类调用,则编译器将自动插入对super()的调用 - 无参数超类构造函数。这样做的必然结果是,如果没有进行这样的调用,并且超类没有无参数构造函数,那么它就是编译器错误。

来自JLS §8.8.7

  

构造函数体的第一个语句可能是对同一个类或直接超类(§8.8.7.1)的另一个构造函数的显式调用。

     

...

     

如果构造函数体不是以显式构造函数调用开始并且声明的构造函数不是原始类Object的一部分,那么构造函数体隐式地以超类构造函数调用“super();”开头,调用它的直接超类的构造函数,不带参数。

答案 2 :(得分:2)

只需创建一个具有附加参数[s]的构造函数,并使用super调用超类构造函数:

public class SalariedEmployee extends Employee {
    //instance fields or attributes of employee
    public SalariedEmployee(String name, String extensionNumber, int salary) {
       super(name,extensionNumber);
       // more logic
    } 
}

答案 3 :(得分:2)

如果子类SalariedEmployee有一个附加字段,那么你可以创建一个接受这个参数的构造函数,然后调用父抽象类构造函数:

public class SalariedEmployee extends Employee {
    private String param;

    public SalariedEmployee(String name, String extensionNumber, String param) {
        super(name, extensionNumber);
        // do something with 'param', e.g.
        this.param = param;
    }
}