user2088260
user2088260

Reputation:

Abstract class constructor initialization

I was looking simple abstraction example as follows ,

public abstract class Employee {
    private String name;
    private String address;
    private int number;

    public Employee(String name, String address, int number) {
        System.out.println("Constructing an Employee");
        this.name = name;
        this.address = address;
        this.number = number;
    }
}

public class Salary extends Employee {
    private double salary; //Annual salary

    public Salary(String name, String address, int number, double salary) {
        super(name, address, number);
        setSalary(salary);
    }
}

public class AbstractDemo {
    public static void main(String[] args) {
        Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
        Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
    }
}

Here I have an abstract base class and concrete sub-classes. The abstract class has 3 parameters in constructor and subclass has four, but when I initialize both the abstract and concrete class in the main method, both constructors are passed 4 parameters and using setSalary() method I am able to calculate a salary for both s and e even thought the Employee abstract class only takes 3 parameters.

How is this happening? Could someone please help me with this?

Upvotes: 2

Views: 1919

Answers (2)

Lucas
Lucas

Reputation: 3281

In both cases you are creating an instance of Salary class, thus the constructor that's being called comes from Salary class.

Upvotes: 0

TypeIA
TypeIA

Reputation: 17258

I'm not sure I understand what you're saying about computesalary() (which isn't in your sample code), but I suspect the confusion might be about this line:

Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

Here, note that even though you're assigning the reference to a variable of type Employee, you're still creating a Salary object. Therefore you still call the Salary derived class' constructor, which has 4 arguments. This line of code is doing exactly the same thing as the line above it, and executing exactly the same code path. The only difference is that the reference to the newly-created object gets stored in a variable with the base class' type.

As Thomas points out, this would call the base class 3-argument constructor:

Employee e = new Employee("John Adams", "Boston, MA", 2);

But this wouldn't be valid code since Employee is abstract.

Upvotes: 4

Related Questions