简体   繁体   中英

Abstract Methods and Constructors

First off, this isn't an assignment question. It's a revision question from past exam papers.

Ok so the question is:

Implement an abstract base class called Employee that is used to hold and access basic information about an employee eg name, address, etc. This class should also define an abstract method called earnings() that returns the weekly pay for each type of employee. The class should include a suitable constructor and accessor methods to retrieve information about the employee.

The code I have so far is:

abstract public class Employee {

    public String Full_Name;
    public int IDNum;
    public String FullAddress;
    public int hours_worked;
    public int hour_pay;

    Employee(String name, int ID, String Address){
        Full_Name = name;
        IDNum = ID;
        FullAddress = Address;
    }

    abstract public int earnings(){
        return int week_Sal = hours_worked*hour_pay;
    }

}

So my question is, how would I pass the different parameters for each employee into the earnings method, so I can then calculate their earnings?

In java, an abstract method declaration doesn't include a method body. You just declare that the method should exist; non-abstract subclasses of the class have to provide a version of the method.

This is an example of what the question is looking for:

abstract public class Employee {

    public String Full_Name;
    public int IDNum;
    public String FullAddress;

    Employee(String name, int ID, String Address){
        Full_Name = name;
        IDNum = ID;
        FullAddress = Address;
    }

    abstract public int earnings();
}

public class HourlyEmployee extends Employee {
    private int hours_worked;
    private int hour_pay;

    HourlyEmployee(String name, int ID, String Address, int hour_pay) {
        super(name, ID, Address);
        this.hour_pay = hour_pay;
    }
    public void setHoursWorked(int hours_worked) {
        this.hours_worked = hours_worked;
    }
    @Override
    public int earnings() {
        return hours_worked * hour_pay;
    }
}

public class CEO extends Employee {
    private long year_pay;
    CEO(String name, int ID, String Address, long year_pay) {
        super(name, ID, Address);
        this.year_pay = year_pay;
    }
    @Override
    public int earnings() {
        // Convert yearly pay to weekly pay
        return (int) (year_pay / 52);
    }
}

The base class just declares that there's a method which returns the weekly earnings. Subclasses provide their own version of the method, and each subclass could implement the method in a completely different way.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM