Abstract Classes & Constructors

If I have an abstract class called Employee having a constructor:

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

How am I supposed to write the constructor of a subclass named SalariedEmployee having an additional attribute (not in the super class) ?

Jon Skeet
people
quotationmark

You just write a constructor which is able to provide the name and extensionNumber values to the superclass constructor, and do whatever else you like.

I would personally make the Employee constructor protected as well, given that it really is only available to subclasses. Note that apart from that aspect, there's really no difference between the use of constructors in abstract classes and in concrete classes.

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
    }
}

Note that it's not required that you have parameters matching the parameters of the superclass, so long as you can provide them in the super call. For example:

public class SalariedEmployee extends Employee {
    ...

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

(You might also want to consider making extensionNumber an int instead of a String, as it really is likely to be a plain number - whereas full phone numbers are best stored as strings.)

people

See more on this question at Stackoverflow