Lesson 12 of 20

Abstract Classes

Abstract Classes

An abstract class can have both concrete and abstract methods. You cannot instantiate it directly — only subclasses:

abstract class Shape {
    abstract double area();   // subclasses must implement this

    void describe() {         // concrete method shared by all
        System.out.println("Area: " + area());
    }
}

class Circle extends Shape {
    double radius;
    Circle(double r) { this.radius = r; }

    @Override
    double area() { return Math.PI * radius * radius; }
}

When to Use Abstract Classes vs Interfaces

  • Use an interface when you only need a contract (method signatures)
  • Use an abstract class when you want shared state (fields) and partial implementation
Shape s = new Circle(5);
s.describe();  // Area: 78.53981633974483

Your Task

Create an abstract class Employee with:

  • protected String name, protected double hourlyRate
  • Constructor Employee(String name, double hourlyRate)
  • Abstract double hoursWorked()
  • Concrete double pay() returning hourlyRate * hoursWorked()
  • toString() returning "<name> earns $<pay>"

Subclasses:

  • FullTime: hoursWorked() returns 40
  • PartTime(double hours): hoursWorked() returns the given hours

Print Alice (FullTime, 25/hr)andBob(PartTime,25/hr) and Bob (PartTime, 20/hr, 20 hrs).

TeaVM (WASM) loading...
Loading...
Click "Run" to execute your code.