Tracing totals through an abstract fare class

A transit app models fares with the Java classes below. The superclass Ticket is abstract: it stores the base fare through its constructor and defines total(), which relies on a surcharge() method that only the subclasses implement.


Java
abstract class Ticket {
    protected final double baseFare;

    Ticket(double baseFare) {
        this.baseFare = baseFare;
    }

    abstract double surcharge();

    double total() {
        return baseFare + surcharge();
    }
}

class StudentTicket extends Ticket {
    StudentTicket() {
        super(12.00);
    }

    double surcharge() {
        return -3.50;
    }
}

class PeakTicket extends Ticket {
    PeakTicket(double fare) {
        super(fare);
    }

    double surcharge() {
        return 0.20 * baseFare;
    }
}


The program then runs these statements:


Java
Ticket student = new StudentTicket();
Ticket peak = new PeakTicket(15.00);


Give the value returned by student.total() and the value returned by peak.total(), each in dollars to two decimal places.

Your answers

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Abstract Methods and Abstract Classes Questions: