Abstract Classes

Sometimes related objects need the same stored data and helper methods, but one operation depends on the particular kind of object. An abstract class is a class that cannot be used directly to create an object, although subclasses can use its code and data. In Java, you declare it with abstract. This lets you supply a useful partial implementation while requiring suitable subclasses to complete it.

Shared code and missing bodies

An abstract method declares an operation without supplying its implementation. In Java, its declaration includes abstract and ends with a semicolon rather than a method body. A class that declares an abstract method must itself be abstract.


Consider a library that represents measurements:


Java
abstract class Reading {
    private final String unit;

    protected Reading(String unit) {
        this.unit = unit;
    }

    public String unit() {
        return unit;
    }

    public abstract double value();
}


The unit() method has a body that every subclass can use. The value() declaration specifies a required operation and its return type, but supplies no calculation. A temperature reading and another kind of reading can obtain their values differently.


The class also has a constructor. It initializes the shared unit field when a subclass object is created. Being abstract does not prevent a class from storing data, declaring constructors, or providing implemented methods.


Two panels compare methods supplied by an abstract class and its concrete subclass.



Construction and subclasses

You cannot write new Reading("degrees Celsius"), because Reading is abstract. You can, however, complete its missing operation in a concrete class:


Java
class TemperatureReading extends Reading {
    private final double celsius;

    public TemperatureReading(double celsius) {
        super("degrees Celsius");
        this.celsius = celsius;
    }

    public double value() {
        return celsius;
    }
}


Creating a TemperatureReading runs its constructor, which calls the Reading constructor through super(...). The object then has the shared unit data and an implementation of value().


A concrete subclass must provide or inherit valid implementations of every required abstract method. An implementation must match the required method's name and parameter types, have a compatible return type, and preserve the required accessibility. Here, the implementation of the public value() method is also public.


Class declaration

Unimplemented abstract methods

Direct object creation

Abstract class

May remain

Not permitted

Abstract subclass

May inherit unresolved requirements

Not permitted

Concrete subclass

None may remain

Permitted when its constructor is accessible


An abstract subclass may leave an inherited requirement unresolved without repeating the method declaration. Conversely, an abstract class may have no abstract methods at all. The abstract class modifier still prevents direct object creation.

Checking whether a class is complete

When several abstract methods are involved, count distinct requirements and identify which already have valid implementations:


Nunresolved=Nrequired−Nimplemented.N_{\text{unresolved}} = N_{\text{required}} - N_{\text{implemented}}.


Here, the implemented count includes only implementations that satisfy the required methods. Include suitable implementations inherited from earlier classes; do not count unrelated helper methods.


If unresolved requirements remain, the subclass must remain abstract or gain the missing implementations. If none remain, it can be declared concrete. Having no unresolved methods does not remove an explicit abstract modifier.



Choose an abstract method when the shared class can specify the operation but cannot supply an appropriate common implementation. Keep genuinely shared behavior in methods with bodies. This gives subclasses a clear responsibility without making them repeat working code.

What to remember

  • Abstract classes cannot be constructed directly, but their constructors initialize subclass objects.
  • Abstract methods declare required operations without bodies.
  • Concrete subclasses must satisfy every abstract-method requirement, directly or through inherited implementations.
  • An abstract class can contain both implemented and abstract methods, or no abstract methods at all.

Example: Completing a Parking Rate

A garage charges an entry fee of 180 cents plus 240 cents for each whole hour parked. Assume hours is a nonnegative integer. The abstract class ParkingRate supplies shared data and code but cannot be constructed directly. The Java draft below deliberately leaves GarageRate unfinished.


Java
abstract class ParkingRate {
    private final int entryFeeCents;

    protected ParkingRate(int entryFeeCents) {
        this.entryFeeCents = entryFeeCents;
    }

    protected int entryFeeCents() {
        return entryFeeCents;
    }

    public abstract int chargeCents(int hours);
    public abstract String receiptLabel();
}

abstract class HourlyRate extends ParkingRate {
    protected HourlyRate(int entryFeeCents) {
        super(entryFeeCents);
    }

    public String receiptLabel() {
        return "Hourly parking";
    }
}

class GarageRate extends HourlyRate {
    public GarageRate() {
        super(180);
    }
}


a) Can you construct an object using new HourlyRate(180)? Identify what GarageRate still needs before its declaration can compile.


An abstract method declares a required operation without giving its implementation. ParkingRate declares ________ such methods. HourlyRate supplies an implementation for ________ of them: receiptLabel().


The unresolved operation is chargeCents(int hours). HourlyRate is allowed to leave it unresolved because that class is abstract. However, new HourlyRate(180) is prohibited because the class is explicitly abstract.


GarageRate is declared concrete, so its draft declaration does not compile. It needs a valid public implementation of chargeCents(int hours). Its constructor initializes the entry fee but does not satisfy this method requirement.


Answer: You cannot construct HourlyRate directly. GarageRate needs one method implementation: chargeCents(int hours).


b) Write the missing method inside GarageRate using the stated charging rule.


The entry fee is available through the inherited entryFeeCents() method. The hourly rate is ________, so multiplying it by the number of hours gives the variable charge in cents.


charge in cents=entry fee in cents+(240 cents/hour)(hours).\text{charge in cents} = \text{entry fee in cents} + (240\ \text{cents/hour})(\text{hours}).


The method must accept one integer parameter and return an integer. It must also remain public, matching the accessibility required by ParkingRate.


Java
public int chargeCents(int hours) {
    return entryFeeCents() + 240 * hours;
}


Answer: Adding this method completes GarageRate. It inherits receiptLabel() and now implements the remaining required operation.


c) After adding the method, what does new GarageRate().chargeCents(3) return, and what charge does that represent in dollars?


Constructing GarageRate calls HourlyRate(180), which calls ParkingRate(180). The shared field therefore stores an entry fee of ________. The abstract-class constructor runs as part of constructing the concrete object.


First calculate the charge for three whole hours:


(240 cents/hour)(3 hours)=720 cents.(240\ \text{cents/hour})(3\ \text{hours}) = 720\ \text{cents}.


The variable charge is ________. Add the entry fee:


180 cents+720 cents=900 cents.180\ \text{cents} + 720\ \text{cents} = 900\ \text{cents}.


Convert cents to dollars using 100 cents per dollar:


900 cents100 cents/dollar=9.00 dollars.\frac{900\ \text{cents}}{100\ \text{cents/dollar}} = 9.00\ \text{dollars}.


Answer: The method returns the integer 900, representing a charge of 9.00 dollars. The method returns cents, so returning 9 would use the wrong unit.

A developer writes the following Java class. Any code attempting to use it is in the same package. Which statement correctly describes the declaration and direct object creation?


Java
abstract class ExportTask {
    protected ExportTask() { }

    public void run() { }
}
Choose an answer

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

A Java team is designing a hierarchy of payment types. One superclass is declared with the abstract modifier, and several subclasses extend it. Match each term on the left with the description of how it behaves in that design.

Match each term
A.

A method declared with a signature and no body, which a subclass must implement before objects of that subclass can be created

B.

A class that new cannot instantiate directly, although it may still hold fields, constructors and fully implemented methods

C.

A class that extends the superclass and implements every inherited body-less method, so new can create its objects

D.

Code that runs through a super(...) call when a subclass object is built, initializing the fields the subclass inherits

E.

A variable declared with the superclass type that can hold any object whose class is a concrete descendant

Abstract class

Abstract method

Reference of abstract type

Constructor in an abstract class

Concrete subclass

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

A sensor library defines a base class Sampler that is never instantiated directly; only its subclasses, such as TemperatureSampler, create objects. The sampleCount() operation has no body in Sampler, and its declaration must require that every concrete subclass have an implementation, declared directly or inherited. Complete the declaration with the missing Java modifier: public int sampleCount();.

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

Extra Practice