0

I'm trying to understand a piece of code my prof gave me regarding constructors and inheritance.

Below is an 'Employee' Class where variables are created and a constructed is created to initialize said variables. This part I get pretty well.

public abstract class Employee {

private int employeeID;
private String firstName;
private String lastName;
private ArrayList<Paycheck> listOfPaychecks;


Employee(int employeeID, String firstName, String lastName, ` 
         ArrayList<Paycheck> listOfPaychecks) {

    this.employeeID=employeeID;
    this.firstName=firstName;
    this.lastName=lastName;
    this.listOfPaychecks=listOfPaychecks;
}

Below, she provided a different class named SalariedEmployee which extends the Employee class. She created a variable annualSalary.

This is where I'm getting confused, I see that she created two constructors.

public class SalariedEmployee extends Employee {

double annualSalary;


SalariedEmployee(SalariedEmployee s) {
    super(s.getEmployeeID(), s.getFirstName(), s.getLastName(), 
          s.getListOfPaychecks());
    this.annualSalary = s.annualSalary;
}

SalariedEmployee(int employeeID, String firstName, String lastName, 
                 ArrayList<Paycheck> listOfPaychecks,
                 double annualSalary) {
    super(employeeID, firstName, lastName, listOfPaychecks);
    this.annualSalary = annualSalary;
}

What is the point of creating two constructors? I see the first one, she created a variable 's' and it's getting the variables from the Employee class' constructor. Is this just to set the s variable to the returning variables in the Employee class?

Can someone help me understand why do we create two constructors? I'm sorry if my vocab is not that well. I am still learning.

  • The first is a [copy constructor](https://www.geeksforgeeks.org/copy-constructor-in-java/). It's really just a convenience method – Phil Feb 13 '18 at 00:08
  • https://beginnersbook.com/2013/05/constructor-overloading/ – PM 77-1 Feb 13 '18 at 00:09
  • 1. You can create as many as constructors you want, as long as the parameters are different. 2. You can just create one constructor, which is the second one you mentioned. This constructor is able to finish all the attribute assigning. The first constructor is aim to accept an Employee object. Of course you can achieve this by calling SalariedEmployee(s.getEmployeeID(),s.getFirstName(), s.getLastName(), s.getListOfPaychecks(), s.annualSalary). Apparently, this is not friendly when coding. – Bejond Feb 13 '18 at 02:01

0 Answers0