Skip to content

Java OOP

0/36 lessons · 0% complete

— XP

Java OOP · Module 10

Abstraction as a design pillar

Constructors in abstract classes, and hiding the 'how' behind the 'what'

22m55 XP
→→→

What you'll be able to do

  • Define abstraction and separate it from encapsulation
  • Explain why an abstract class has a constructor and who runs it
  • Use the template-method shape: fixed algorithm, variable steps
  • Choose between an abstract class and a concrete class deliberately
1

Abstraction

Abstraction: the caller sees the what, never the how

You drive a car without knowing how fuel injection works. The pedal is the abstraction; the engine is the implementation.

Abstraction is the third pillar of OOP: exposing a simple, stable set of operations while hiding the details of how they are carried out. In Java you build abstraction with: - abstract classes — a partial implementation plus a required contract (this module); - interfaces — a pure contract with no state (Module 11). The practical test of good abstraction: *can the implementation change completely without any caller noticing?* If PaymentProcessor.process() switches from one gateway to another and no calling code changes, the abstraction did its job.

Encapsulation vs Abstraction — the interview favourite

Encapsulation

hides **data**

Main.java
1class Account {
2 private double balance; // hidden state
3 public void deposit(double a) { }
4}
  • Mechanism: private + accessors
  • Question answered: *who may touch this field?*
  • Protects invariants (Module 4)

Abstraction

hides **implementation**

Main.java
1abstract class Payment {
2 abstract double fee(); // contract only
3 void process() { } // shared algorithm
4}
  • Mechanism: abstract classes and interfaces
  • Question answered: *what can this type do?*
  • Enables swapping implementations
Template method: one algorithm, several fillings

`process()` is written once and never overridden. Add a `WalletPayment` with a flat fee of 1 and put it in the array — `process()` stays untouched.

Output
Press Run to execute this example.

Mark the algorithm `final`

In production you would declare final void process(). The final keyword forbids overriding, so subclasses can fill in the steps (fee(), label()) but cannot rewrite the sequence — the parent keeps control of the algorithm while delegating the details. That is the template method pattern in one line.

Prove it — coding challenges

2

Constructors in Abstract Classes

Why an abstract class needs a constructor

You can never write `new Account(...)` — so who calls `Account(...)`? Every subclass, on every creation.

An abstract class usually has state (fields such as owner, balance, amount) that every subclass shares. That state still has to be initialised exactly once, with validation, when an object is created. So: - An abstract class may declare constructors — and normally should. - You cannot invoke them with new. - They run as part of the chain from Module 6: new Savings(...) → super(...) → the abstract class's constructor. The rule 'abstract classes cannot be instantiated' does not mean 'abstract classes cannot be constructed'. Their constructor runs on behalf of every concrete subclass object.

The abstract constructor really executes

The abstract class's constructor prints first — proof that it really runs. Try removing `super(owner, balance);` from Savings to see the chain break.

Output
Press Run to execute this example.

Should this class be abstract? A checklist

  1. Would a bare instance of it be meaningless in your domain (new Animal(), new Payment(), new Shape())? → abstract.
  2. Is there at least one operation every subtype must provide but none can share? → abstract method.
  3. Is there shared state or shared algorithm? → abstract class rather than an interface.
  4. No shared state and you may need multiple unrelated capabilities? → interface (Module 11).
  5. None of the above? Keep it a plain concrete class — do not add abstraction you do not need.

Common mistakes

WrongBelieving an abstract class cannot have a constructor.
WhyIt can, and subclasses must call it with `super(...)` to initialise shared state.
FixGive the abstract class a constructor for its fields, exactly as you would in a normal class.
WrongOverriding the template algorithm in every subclass.
WhyYou lose the single, consistent sequence that the base class was created to guarantee.
FixOverride only the abstract steps; mark the algorithm `final`.
WrongUsing 'abstraction' and 'encapsulation' as synonyms.
WhyEncapsulation hides data inside one object; abstraction hides an implementation behind a type.
Fixprivate field → encapsulation. abstract method / interface → abstraction.

Lesson playground

Free practice

A Report base class fixes the layout and leaves the content to subclasses. Add an `InventoryReport` and generate both.

Output
Press Run to execute this example.

Check understanding

Quiz

Question 1 of 5

An abstract class with a constructor. What is printed?

Main.java
1abstract class Vehicle {
2 protected String brand;
3
4 Vehicle(String brand) {
5 this.brand = brand;
6 System.out.println("Vehicle built: " + brand);
7 }
8
9 abstract int wheels();
10}
11
12class Bike extends Vehicle {
13 Bike(String brand) {
14 super(brand);
15 System.out.println("Bike ready");
16 }
17
18 @Override
19 int wheels() {
20 return 2;
21 }
22}
23
24public class Main {
25 public static void main(String[] args) {
26 Vehicle v = new Bike("Giant");
27 System.out.println(v.wheels());
28 }
29}

Summary

  • Abstraction hides *how* behind a stable *what*; encapsulation hides data inside an object.
  • Abstract classes have constructors that run through `super(...)` for every subclass object.
  • Template method: concrete algorithm in the parent, abstract steps in the children.
  • Choose abstract when a bare instance is meaningless or a subtype must supply behaviour.