How to properly use multiple constructors of my superclass in the subclass? (Java)

829 views Asked by At

If I have a superclass with some attributes and 2 constructors like for example

class Employe {
    private final String nom;
    private double income;
    private double occupation;

    public Employe(String n, double i, double o) {
        nom = n;
        income = i;
        occupation = o;
    }

    public Employe(String n, double i) {
        this(n, i, 100);
    }
}

and a subclass

class Manager extends Employe {

    private int days;
    private int clients;
}

If I wanna make use of both cosntructors of the superclass do I have to define

public Manager(String nom, double sal, int d, int c, double occ) {
    super(nom, sal, occ);
    days = d;
    clients = c;
}

public Manager(String nom, double sal, int d, int c) {
    super(nom, sal);
    days = d;
    clients = c;
}

or is there any better way I could prevent the duplication of code of the attributes days and clients in the class Manager?

2

There are 2 answers

0
Kaushik Patel On

There is no way to implicitly call the defined constructor of the Parent class as Constructors are not inherited during inheritance.

So you would have to use super for calling the Parent class constructor.

For you following Query or is there any better way I could prevent the duplication of the instantiation of the attributes days and clients in the class Manager , you can do the following

public Manager(String nom, double sal, int d, int c, double occ) {
    super(nom, sal, occ);
    days = d;
    clients = c;
}

public Manager(String nom, double sal, int d, int c) {
    super(nom, sal, 100,d,c);
}

But this been better depends on what you want to achieve in your case.

0
Stephen C On

In your example you could also write this:

public Manager(String nom, double sal, int d, int c, double occ) {
    super(nom, sal, occ);
    days = d;
    clients = c;
}

public Manager(String nom, double sal, int d, int c) {
    this(nom, sal, 100, d, c);
}

which avoids duplicating the assignments for days and clients. However, in the process you are hard-wiring the superclass default for occupation into the subclass. That may be a bad thing.

The other point is that there is nothing forcing you to create multiple constructors, either in the superclass or the subclass. If the burden of coding the overloads is too great, you could skip it.