Thuta Learning
Java
AdvancedProgrammingBeginner

Abstraction

JavaLesson 2130 min

What you'll walk away with

  • Declare abstract classes and abstract methods and explain why they cannot be created with new
  • Apply the rule that a concrete subclass must implement every abstract method, and read the compiler error
  • Mix fields, constructors and concrete methods with abstract methods in one abstract class
  • Write a template method and choose between an abstract class and an interface

Explain it simply

Abstraction in plain language

Abstraction means hiding complicated details and showing users only the operations they actually need. To drive a car you need the accelerator and the brake, not an understanding of how fuel burns inside the engine. Switch to another brand of car and the pedals are the same, so you do not relearn how to drive.

In Java you can declare an operation such as "pay" in an abstract class and leave the details, card or wallet, to subclasses. The calling code only ever sees the pedals.

Problem → Why → Solution

The problem: half-finished objects and empty methods

Before learning about abstract, a developer writes an ordinary Payment class whose pay() does nothing, expecting subclasses to override it. Later, whoever writes BankTransferPayment forgets to override pay(). The code compiles and runs, orders are marked as paid, and no money ever moves. Somewhere there may even be a plain new Payment() that cannot do anything at all.

Payment.java
class Payment {
  void pay(double amount) {
    // subclasses should override this... hopefully
  }
}

class BankTransferPayment extends Payment {
  // forgot to override pay(): compiles, silently does nothing
}

Payment p = new Payment();   // allowed, but what kind of payment is this?

Let the compiler enforce the rule

The rule "every subclass must write pay()" lived only in people's memory. Make Payment abstract and pay() an abstract method with no body, and the rule moves into the code: the compiler rejects new Payment() and refuses to compile any subclass that does not write pay().

Core concept: abstract classes and abstract methods

Writing abstract class Payment means Payment can no longer be created directly with new; the compiler says "Payment is abstract; cannot be instantiated". Payment is a concept, and the things that really exist are concrete classes such as CardPayment and WalletPayment. Payment is still fully usable as a type: variables, parameters and a List<Payment> can hold any concrete subclass object.

An abstract method has a signature and no body: abstract void pay(double amount); ends with a semicolon. Any class that has an abstract method must itself be abstract. Every concrete (non-abstract) subclass must implement all the abstract methods it inherits; miss one and you get "CardPayment is not abstract and does not override abstract method pay(double) in Payment". A subclass that is itself abstract may pass the job further down. Because an abstract method exists only to be overridden, it cannot also be private, static or final; the compiler rejects each of those combinations.

An abstract class is not an empty shell. It can mix fields, constructors and concrete methods with bodies alongside its abstract methods. Its constructor runs through a subclass's super(...) and initialises shared fields. Its concrete methods can call its abstract methods, and at runtime the subclass's implementation does the work. So the abstract class owns "which steps happen", and subclasses fill in only "how this step is done".

Abstraction is more than a keyword; it is a design decision. If checkout code knows only Payment and never CardPayment, switching card providers cannot break checkout. Java offers two tools for building abstractions, abstract classes and interfaces. Interfaces get their own lesson (lesson 23), and the deeper section below compares the two.

An abstract class is a form with required blanks
  1. Abstract class writes the shared part
  2. Abstract methods are the blanks
  3. Concrete subclass fills every blank
  4. Clients use only the abstract type

Leave one blank empty and the compiler rejects the form; that is the key difference from an empty method in a normal class.

General pattern

java
abstract class BaseType {
  abstract ReturnType requiredStep(Params p);   // no body

  ReturnType sharedStep() { ... }               // concrete method
}

class ConcreteType extends BaseType {
  @Override
  ReturnType requiredStep(Params p) { ... }     // must implement
}

BaseType value = new ConcreteType();            // use the abstract type

Write methods that every subclass shares with a body, make the ones that must differ abstract, and declare client variables with the abstract type.

Worked example: a Payment abstraction

Payment owns one shared method, which shows the currency, and an abstract pay() that every subclass must write. CardPayment and WalletPayment each implement pay() their own way. The variables in main are declared as Payment, so main never cares which subclass it holds.

Main.java
public class Main {
  public static void main(String[] args) {
    Payment payment = new CardPayment();
    payment.showCurrency();
    payment.pay(49.99);

    Payment wallet = new WalletPayment("mobile wallet");
    wallet.pay(12.5);

    // Payment unknown = new Payment();   // compile error: Payment is abstract
  }
}

abstract class Payment {
  abstract void pay(double amount);

  void showCurrency() {
    System.out.println("Currency: USD");
  }
}

class CardPayment extends Payment {
  @Override
  void pay(double amount) {
    System.out.println("Paid " + amount + " using card.");
  }
}

class WalletPayment extends Payment {
  private final String provider;

  WalletPayment(String provider) {
    this.provider = provider;
  }

  @Override
  void pay(double amount) {
    System.out.println("Paid " + amount + " using " + provider + ".");
  }
}

Code breakdown

  1. Abstract classabstract class Payment {

    abstract forbids new Payment(). Uncomment that line in main and the program no longer compiles.

  2. Abstract methodabstract void pay(double amount);

    No body, just a semicolon. It states the promise "can pay" and leaves how to pay to the subclasses.

  3. Shared concrete methodvoid showCurrency() {

    Behaviour that every subclass shares is written once in the abstract class; CardPayment inherits showCurrency() without writing it.

  4. Implementation with its own stateprivate final String provider;

    WalletPayment keeps its provider name in its own field and uses it in pay(). Neither Payment nor main knows the field exists; that is exactly the detail the abstraction hides.

You should see
Currency: USD
Paid 49.99 using card.
Paid 12.5 using mobile wallet.

The template method: the parent owns the steps

The most powerful use of an abstract class is the template method pattern. The parent fixes the order of steps (validate, charge, print a receipt) inside a final method and leaves only the step that varies abstract. Because checkout() is final, no subclass can override it to skip the validation.

Checkout.java
public class Checkout {
  public static void main(String[] args) {
    PaymentProcessor card = new CardProcessor();
    card.checkout(25.0);
    card.checkout(-3.0);
    card.checkout(8.5);
  }
}

abstract class PaymentProcessor {
  final void checkout(double amount) {          // the fixed recipe
    if (amount <= 0) {
      System.out.println("Rejected: amount must be positive");
      return;
    }
    String reference = charge(amount);          // the step that varies
    System.out.printf("Receipt %s for %.2f%n", reference, amount);
  }

  protected abstract String charge(double amount);
}

class CardProcessor extends PaymentProcessor {
  private int counter = 0;

  @Override
  protected String charge(double amount) {
    counter++;
    return "CARD-" + counter;
  }
}

The output is Receipt CARD-1 for 25.00, then Rejected: amount must be positive, then Receipt CARD-2 for 8.50. The negative amount never reaches charge(), so the counter does not move.

Abstract class or interface?

NeedAbstract classInterface
Instance fields and stateYesNo (constants only)
ConstructorsYesNo
How many a class can takeExtends only oneImplements many
Methods with bodiesYesYes, as default methods
Best forShared state and fixed stepsA capability contract

A good rule of thumb: start with an interface, and add an abstract class when shared state or a fixed sequence of steps appears. Combining them is common too: interface Payment is the contract, and abstract class AbstractPayment is a convenient base that most implementations extend.

In real projects

Abstraction in real projects

The JDK is full of abstract classes. java.io.InputStream declares an abstract read() method, and streams with very different sources (a file, a network socket, a byte array in memory) each implement it. Concrete methods such as readAllBytes() are built on top of read(), so every subclass gets them for free. java.util.AbstractList similarly gives you a whole read-only List once you write just get() and size().

  • Payment providers: an abstract PaymentProcessor owns validation, logging and retries, and each provider implements only the part that calls its API.
  • File storage: an abstract StorageProvider offers the same save() and load() over a local disk, a cloud bucket or an in-memory store for tests.
  • Report generators: an abstract base handles the header, footer and page numbers, while sales and inventory reports write only their body.

Common mistakes

Common mistakes with abstraction

Trying to create an abstract class with new

new Payment() fails with "Payment is abstract; cannot be instantiated". Create a concrete subclass and store it in a Payment variable: Payment p = new CardPayment();. If you feel you need to instantiate the abstract class itself, maybe it should not be abstract.

Leaving one abstract method unimplemented

The day you add a new abstract method refund() to Payment, every concrete subclass fails with "is not abstract and does not override abstract method refund(double)". That is a good error: it lists every place the new rule must be filled in. Do not silence it with empty bodies.

Calling an abstract method from the constructor

If Payment()'s constructor calls label(), and WalletPayment's label() uses its provider field, the output is "Created null wallet": while the parent constructor runs, the subclass's fields are not initialised yet. Never call overridable methods from a constructor.

Leaking implementation details into the abstract API

Putting getCardNumber() on the abstract Payment forces wallet and bank-transfer subclasses to return meaningless values, and clients start checking instanceof again. Keep only operations that every implementation can honour on the abstract type.

Mini challenge

Mini challenge: subscription plans

Write an abstract class Plan for subscription plans. Every plan has a name and a monthly price; the yearly price follows one rule for all plans: monthly price times 12, minus 10%. Write a BasicPlan (5.00 a month) and a ProPlan that charges 12.00 per seat.

  • Declare name() and monthlyPrice() as abstract methods
  • Write yearlyPrice() and summary() once, as concrete methods in Plan
  • ProPlan takes its number of seats through its constructor
  • Loop over a List<Plan> and print each summary()
Plans.java
import java.util.List;

public class Plans {
  public static void main(String[] args) {
    List<Plan> plans = List.of(new BasicPlan(), new ProPlan(3));
    // TODO: print summary() for every plan
  }
}

abstract class Plan {
  // TODO: abstract String name();
  // TODO: abstract double monthlyPrice();

  double yearlyPrice() {
    // TODO: monthly * 12, minus 10%
  }

  String summary() {
    // TODO: "<name>: <monthly>/month, <yearly>/year" with 2 decimals
  }
}

// TODO: BasicPlan -> name "Basic", 5.00 a month
// TODO: ProPlan(int seats) -> name "Pro (<seats> seats)", 12.00 per seat

Expected: Two lines: "Basic: 5.00/month, 54.00/year" and "Pro (3 seats): 36.00/month, 388.80/year".

Show hint

In summary(), call String.format("%s: %.2f/month, %.2f/year", ...) with name(), monthlyPrice() and yearlyPrice(). The subclass implementations run at runtime, so no subclass rewrites summary().

Show solution
Plans.java
import java.util.List;

public class Plans {
  public static void main(String[] args) {
    List<Plan> plans = List.of(new BasicPlan(), new ProPlan(3));
    for (Plan plan : plans) {
      System.out.println(plan.summary());
    }
  }
}

abstract class Plan {
  abstract String name();

  abstract double monthlyPrice();

  double yearlyPrice() {
    return monthlyPrice() * 12 * 0.9;
  }

  String summary() {
    return String.format("%s: %.2f/month, %.2f/year",
        name(), monthlyPrice(), yearlyPrice());
  }
}

class BasicPlan extends Plan {
  @Override
  String name() {
    return "Basic";
  }

  @Override
  double monthlyPrice() {
    return 5.00;
  }
}

class ProPlan extends Plan {
  private final int seats;

  ProPlan(int seats) {
    this.seats = seats;
  }

  @Override
  String name() {
    return "Pro (" + seats + " seats)";
  }

  @Override
  double monthlyPrice() {
    return 12.00 * seats;
  }
}

Quick quiz 1 / 3

Given abstract class Shape { abstract double area(); } and a Circle that extends Shape and implements area(), which line compiles?

Quick quiz 2 / 3

What happens if you write class Square extends Shape { } without area()?

Quick quiz 3 / 3

Can an abstract class have a constructor?

What to remember

  • An abstract class cannot be created with new, but it is fully usable as the type of variables, parameters and collections.
  • Abstract methods have no body, and every concrete subclass must implement all of them or fail to compile.
  • An abstract class can mix fields, constructors and concrete methods with abstract ones, which enables the template method pattern.
  • Choose an interface for a pure contract and an abstract class when you need shared state or fixed steps.

Java Language Specification, Java SE 25 — Oracle

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Abstraction | Thuta Learning