Core Java

13 — Abstraction & Interfaces

Previous: 12 Inheritance & Polymorphism · Next: 14 Static & Enums

▶️ java pkg1core/core13AbstractionDemo.java · java pkg1core/core14InterfacesDemo.java


Abstract classes — partial implementation

java
1abstract class Payment {2    protected final double amount;3    Payment(double amount) { this.amount = amount; }4 5    abstract String method();      // subclass MUST implement6    abstract void authorize();7 8    final void process() {         // template method — fixed algorithm9        validate();10        authorize();11        System.out.println("Charged " + amount);12    }13    void validate() {14        if (amount <= 0) throw new IllegalArgumentException();15    }16}

Use when subclasses share state and concrete behavior.


Interfaces — contracts

java
1interface Drawable {2    void draw();                   // implicitly public abstract3    default void highlight() {     // Java 8+ — optional impl4        System.out.println("highlight");5    }6    static void info() {           // utility, not inherited7        System.out.println("Drawable v1");8    }9}
  • A class implements one or more interfaces
  • Interface = can-do capability (Comparable, Runnable, Serializable)

Abstract class vs interface

Abstract class Interface
Inheritance extends (one) implements (many)
State Can have fields Only constants (before records)
Use when Shared base + partial impl Capability / multiple roles

Multiple interfaces

java
1class Button implements Drawable, Clickable, Serializable { ... }

Java supports multiple inheritance of type through interfaces.

Next → 14 Static & Enums Related → 01 Core Java