// Employee.java
// Abstract base class Employee

public abstract class Employee {
    private String firstName;
    private String lastName;

    // Constructor
    public Employee( String first, String last ) {
        firstName = first;
        lastName = last;
    }

    // Return the first name
    public String getFirstName() { return firstName; }

    // Return the last name
    public String getLastName() { return lastName; }
    public String toString() { return firstName + ' ' + lastName; }

    // Abstract method that must be implemented for each
    // derived class of Employee from which objects
    // are instantiated.

    public abstract double earnings();
}



// Boss class derived from Employee. Can be a separate file.

public final class Boss extends Employee {
    private double weeklySalary;

    // Constructor for class Boss
    public Boss( String first, String last, double s) {
        super( first, last ); // call superclass constructor
        setWeeklySalary( s );
    }

    // Set the Boss's salary
    public void setWeeklySalary( double s ) { weeklySalary = ( s > 0 ? s : 0 ); }

    // Get the Boss's pay
    public double earnings() { return weeklySalary; }

    // Print the Boss's name
    public String toString() {
        return "Boss: " + super.toString();
    }
}

 

// Test program for employee. Can be a separate file.

import javax.swing.JOptionPane;
import java.text.DecimalFormat;

public class Test {
    public static void main( String args[] ) {
        Employee ref; // superclass reference
        String output = "";

        Boss b = new Boss( "John", "Smith", 800.00 );
        CommissionWorker c = new CommissionWorker( "Sue", "Jones", 400.0, 3.0, 150);
        PieceWorker p = new PieceWorker( "Bob", "Lewis", 2.5, 200 );
        HourlyWorker h = new HourlyWorker( "Karen", "Price", 13.75, 40 );

        DecimalFormat precision2 = new DecimalFormat( "0.00" );

        ref = b; // Employee reference to a Boss

        output += ref.toString() + " earned $" + precision2.format( ref.earnings() ) + "\n" + b.toString() + " earned $" + precision2.format( b.earnings() ) + "\n";

        ref = c; // Employee reference to a CommissionWorker

        output += ref.toString() + " earned $" + precision2.format( ref.earnings() ) + "\n" + c.toString() + " earned $" + precision2.format( c.earnings() ) + "\n";

        ref = p; // Employee reference to a PieceWorker

        output += ref.toString() + " earned $" + precision2.format( ref.earnings() ) + "\n" + p.toString() + " earned $" + precision2.format( p.earnings() ) + "\n";

        ref = h; // Employee reference to an HourlyWorker

        output += ref.toString() + " earned $" + precision2.format( ref.earnings() ) + "\n" + h.toString() + " earned $" + precision2.format( h.earnings() ) + "\n";

        JOptionPane.showMessageDialog( null, output, "Demonstrating Polymorphism", JOptionPane.INFORMATION_MESSAGE );

        System.exit( 0 );

    }
}