Abstract Classes

CSCI 1933 – Introduction to Algorithms and Data Structures
Adriana Picoral

Why Abstract Classes?

  • Hybrid between an interface and a class
  • Non-instantiable because some methods are not defined
  • Useful when some behaviors are known, but others are to be specified later
  • Question: Why would this be helpful?

Practice

Scenario: You are modeling different types of employees at a company.

  1. Create an abstract class Employee, with an abstract method calculatePay() and toString()
  2. Create a concrete class HourlyEmployee that extends Employee with an instance variable hourlyRate and an implementation of calculatePay() that returns hoursWorked * hourlyRate
  3. Create a concrete class SalariedEmployee that extends Employee with an instance variable annualSalary and an implementation of calculatePay() that returns annualSalary / 52 (weekly pay)

Possible Solution

public abstract class Employee {
    protected String firstName;
    protected String lastName;
    protected String employeeID;

    abstract double calculatePay();
    abstract void setName(String first, String last);

    @Override
    public String toString() {
        String out = "Employee ID: " + employeeID;
        out += "\nEmployee Name: " + firstName + " " + lastName;
        out += "\nSalary: " + calculatePay();
        return out;
    }
}

Possible Solution

public class HourlyEmployee extends Employee{
    private double hourlyRate;
    private double hoursWorked;

    public HourlyEmployee(double rate, String ID) {
        hourlyRate = rate;
        super.employeeID = ID;
    }

    public void setName(String first, String last) {
        super.firstName = first;
        super.lastName = last;
    }

    public void addHours(double hours) {
        hoursWorked += hours;
    }

    public double calculatePay() {
        return Math.round(hourlyRate * hoursWorked * 100) / 100.0;
    }
}

Discussion

  • Why can’t you instantiate Employee directly?
  • What would happen if HourlyEmployee did not implement calculatePay()?

Looking Back

A continuum of detail…

  • Interface (not specified, signatures only,not instantiable)
  • Abstract class (partially specified, not instantiable – why?)
  • Class (completely specified, instantiable)