Skip to main content

Java OOP

Abstraction

Complete lesson for Abstraction using LEARNCODEGURU’s 6-level learning model — from basics to advanced practice, with Java OOP and Collections where relevant.

L1

Basics — Abstraction

Section: Java OOP. Show what an object does, hide how it does it — abstract classes, abstract methods, interfaces, real-life examples, and design patterns.

What is abstraction?

  • Abstraction means showing only the essential features of an object and hiding the implementation details.
  • It answers "what does it do?" and hides "how does it do it?".
  • Real life: you drive a car with the steering wheel, accelerator, and brake. You do not need to know how fuel injection or the gearbox works.
  • In Java you achieve abstraction with abstract classes and interfaces. The parent type declares WHAT (abstract methods); each subclass provides HOW (method bodies).
  • Callers work with the abstract type (Vehicle v), so the implementation can change without changing the caller.
abstract class Vehicle {
    abstract void start();   // WHAT every vehicle can do
    abstract void stop();

    void honk() {            // common behaviour, already implemented
        System.out.println("Beep beep!");
    }
}

class Car extends Vehicle {
    @Override
    void start() { System.out.println("Car: push button, engine starts"); } // HOW for a car

    @Override
    void stop() { System.out.println("Car: press brake pedal"); }
}

class Bike extends Vehicle {
    @Override
    void start() { System.out.println("Bike: kick start"); }                // HOW for a bike

    @Override
    void stop() { System.out.println("Bike: squeeze brake lever"); }
}

public class AbstractionDemo {
    public static void main(String[] args) {
        Vehicle[] garage = { new Car(), new Bike() };
        for (Vehicle v : garage) {   // the driver only knows start, honk, stop
            v.start();
            v.honk();
            v.stop();
        }
    }
}

Abstraction in real life — show what it does, hide how it works

A car gives you a steering wheel and pedals, a remote gives you buttons, a coffee machine gives you one start button, and an ATM gives you a Withdraw option. The engine, circuits, heaters, and bank servers stay hidden. In Java, an abstract method is the WHAT and the subclass writes the HOW.

Java abstraction infographic with real-life examples: a car dashboard with steering and brake while the engine and fuel system are hidden, a TV remote with buttons while the circuit and IR signal are hidden, a coffee machine start button while heating and grinding are hidden, an ATM withdraw button while the bank server is hidden, Java code with abstract class Vehicle and class Car implementing start, and abstract class and interface as the two ways Java achieves abstraction.
Java abstraction — essential features visible, implementation details hidden
  • You see: a small set of operations — start(), stop(), withdraw().
  • Hidden: how each operation works, written inside subclasses or implementing classes.
  • Tools: abstract class (0 to 100% abstraction) and interface (full contract).
  • Benefit: callers use Vehicle v; you can swap Car for Bike without changing them.

Real-life examples of abstraction

  • In every example the user works with a small, simple set of controls. The complex machinery stays hidden and can be replaced without retraining the user.
Real-life objectWhat you use (essential)What is hidden (implementation)Java idea
CarSteering, accelerator, brake, gearEngine combustion, fuel injection, ABS logicabstract class Vehicle with start(), stop()
TV remotePower, volume, channel buttonsCircuit board, infrared signal codesinterface RemoteControl
ATMInsert card, enter PIN, withdrawBank server, network, cash countinginterface Atm with withdraw(amount)
Coffee machineChoose drink, press startWater heating, grinding, pressure controlabstract class Beverage with brew()
Smartphone cameraTap the shutter buttonSensor, autofocus, image processingtakePhoto() method
EmailWrite message, click SendSMTP protocol, mail servers, routingsend(to, message) method
Electric switchSwitch on, switch offWiring, current flow, power gridinterface Switchable
Online paymentPay with UPI, card, or net bankingEncryption, bank APIs, fraud checksabstract class Payment with pay()
Google MapsEnter destination, follow routeGPS, shortest-path algorithms, traffic datainterface NavigationService
Washing machineChoose mode, press startMotor speed, water level, timersabstract class WashProgram

Why we need abstraction

  • Reduces complexity: users of a class learn a few methods, not the whole implementation.
  • Flexibility: swap one implementation for another (UPI to card payment, MySQL to PostgreSQL) without changing calling code.
  • Loose coupling: code depends on the abstract type, not on concrete classes.
  • Reusability: common code lives once in the abstract parent; only the changing parts are written in subclasses.
  • Team work: one team writes against the interface while another team implements it.
  • Supports polymorphism: one loop over Vehicle[] works for cars, bikes, and buses.

How to achieve abstraction in Java

ToolHow much abstractionKeywordsExample
Abstract classPartial (0 to 100%): mix abstract and concrete methodsabstract class, extendsabstract class Shape { abstract double area(); }
InterfaceFull contract (100% before Java 8; default and static methods allowed since Java 8)interface, implementsinterface Payable { void pay(double amount); }
Access modifiersHide helper methods and fields inside a classprivate, package-privatePrivate validation methods behind a public withdraw()
Packages and modulesHide whole implementation classesPackage-private classes, module-info.java exportsExport only the API package, keep internal packages hidden

Abstract class

  • Declared with the abstract keyword. It cannot be instantiated with new.
  • It can have abstract methods (no body) and concrete methods (with body), fields, constructors, and static members.
  • A concrete subclass must implement every abstract method, otherwise the subclass must also be declared abstract.
  • Real life: nobody buys "a payment". You pay by UPI, card, or net banking. Payment is an idea (abstract); UPI payment is a real thing (concrete).
abstract class Payment {
    protected final double amount;

    Payment(double amount) {
        this.amount = amount;
    }

    abstract void pay();             // each payment type pays differently

    void printReceipt() {            // same for every payment type
        System.out.println("Paid Rs." + amount + " via " + getClass().getSimpleName());
    }
}

class UpiPayment extends Payment {
    private final String upiId;

    UpiPayment(double amount, String upiId) {
        super(amount);
        this.upiId = upiId;
    }

    @Override
    void pay() { System.out.println("Sending UPI request to " + upiId); }
}

class CardPayment extends Payment {
    private final String last4;

    CardPayment(double amount, String last4) {
        super(amount);
        this.last4 = last4;
    }

    @Override
    void pay() { System.out.println("Charging card ending " + last4); }
}

class NetBanking extends Payment {
    NetBanking(double amount) { super(amount); }

    @Override
    void pay() { System.out.println("Redirecting to bank login"); }
}

public class PaymentDemo {
    public static void main(String[] args) {
        Payment[] payments = {
            new UpiPayment(499, "asha@upi"),
            new CardPayment(1299, "4321"),
            new NetBanking(2500)
        };
        for (Payment p : payments) {
            p.pay();           // caller does not know HOW each one pays
            p.printReceipt();
        }
        // Payment p = new Payment(100); // ERROR: Payment is abstract; cannot be instantiated
    }
}

Abstract method

  • A method declared with abstract and no body. It ends with a semicolon: abstract void sound();.
  • It can exist only inside an abstract class (or an interface, where methods are abstract by default).
  • It is a promise: every concrete subclass must provide the body.
  • It cannot be private, static, or final, because those can never be overridden.
abstract class Animal {
    abstract void sound();                 // OK: no body, ends with ;
    // abstract void eat() { }             // ERROR: abstract methods cannot have a body
    // private abstract void sleep();      // ERROR: illegal combination of modifiers
    // static abstract void info();        // ERROR: illegal combination of modifiers
    // final abstract void run();          // ERROR: illegal combination of modifiers
}

class Dog extends Animal {
    @Override
    void sound() { System.out.println("Dog barks"); }
}

// class Cat extends Animal { }            // ERROR: Cat is not abstract and does not override sound()

abstract class Bird extends Animal { }     // OK: still abstract, may skip sound()

class Parrot extends Bird {
    @Override
    void sound() { System.out.println("Parrot talks"); }
}

public class AbstractMethodDemo {
    public static void main(String[] args) {
        Animal a = new Dog();
        a.sound();            // Dog barks
        new Parrot().sound(); // Parrot talks
    }
}

Rules of abstract classes and abstract methods

RuleAllowed?Notes
Create an object with newNoUse a concrete subclass or an anonymous class
Reference variable of the abstract typeYesShape s = new Circle(2);
ConstructorsYesThey run through super(...) when a subclass object is created
Instance and static fieldsYesShared state for all subclasses
Concrete (normal) methodsYesCommon behaviour written once
Zero abstract methodsYesThe class still cannot be instantiated
main method inside an abstract classYesAn abstract class can be the program launcher
final abstract classNofinal forbids extending, abstract requires it
Abstract method with a bodyNoIt must end with a semicolon
private, static, or final abstract methodNoThese cannot be overridden
Abstract method in a non-abstract classNoThe class must be declared abstract
Subclass skips an abstract methodOnly if the subclass is abstractOtherwise compile error
Override with wider accessYesprotected abstract can become public in the child

Abstraction with interfaces

  • An interface is a pure contract: a list of methods that implementing classes must provide.
  • Methods are public abstract by default. Fields are public static final constants.
  • Since Java 8 an interface can have default and static methods; since Java 9 also private helper methods.
  • A class can implement many interfaces, so unrelated classes can share a capability.
  • Real life: one universal remote control works with a TV and an air conditioner. Each device decides how to react to the same buttons.
interface RemoteControl {
    void powerOn();                // public abstract by default
    void powerOff();
    void setLevel(int level);

    default void mute() {          // Java 8+: shared default behaviour
        setLevel(0);
    }
}

class Television implements RemoteControl {
    public void powerOn() { System.out.println("TV on"); }
    public void powerOff() { System.out.println("TV off"); }
    public void setLevel(int level) { System.out.println("TV volume " + level); }
}

class AirConditioner implements RemoteControl {
    public void powerOn() { System.out.println("AC cooling started"); }
    public void powerOff() { System.out.println("AC off"); }
    public void setLevel(int level) { System.out.println("AC fan speed " + level); }
}

public class RemoteDemo {
    public static void main(String[] args) {
        RemoteControl[] devices = { new Television(), new AirConditioner() };
        for (RemoteControl r : devices) {
            r.powerOn();
            r.mute();      // same button, each device decides how
            r.powerOff();
        }
    }
}

Differences between abstract class and interface

PointAbstract classInterface
Keywordabstract classinterface
Inherited withextends (only one class)implements (many); an interface can extends many interfaces
MethodsAbstract and concreteAbstract, default, static, private (Java 9)
FieldsAny: instance and static, any accessOnly public static final constants
ConstructorsYesNo
Instance stateYesNo
Member accessAny modifierPublic by default (private helpers since Java 9)
Level of abstractionPartial (0 to 100%)Full contract
Multiple inheritanceNoYes
Lambda supportNoYes, if it is a functional interface (one abstract method)
RelationshipIS-A: Car is a VehicleCAN-DO: Car can be Insurable
Real-life analogyA vehicle blueprint with a common engine number and chassisA remote-control contract that any device can follow
Use whenRelated classes share code and stateUnrelated classes share a capability

Differences between abstraction and encapsulation

PointAbstractionEncapsulation
MeaningHide complexity, show only essential operationsHide data, control access to it
FocusWhat an object doesHow its data is protected
LevelDesign levelImplementation level
Achieved byAbstract classes and interfacesprivate fields, getters, setters, access modifiers
Question it answersWhat should the user see?Who may read or change this data?
Real lifeDriving with steering and pedals, without knowing the engineThe engine sealed under a locked bonnet
Java exampleabstract void start();private double balance; with deposit()
Main benefitSimpler use and replaceable implementationsData safety and validation

When to choose an abstract class or an interface

Choose an abstract class whenChoose an interface when
Subclasses share fields (state), like name or idYou only need method signatures (a contract)
You need a constructor to set up common dataUnrelated classes must share a role: Comparable, Runnable
You want to provide partial implementationA class needs several roles at once
You need non-public members (protected helpers)You want lambdas (functional interface)
The classes form a clear IS-A familyYou design a public API that others will implement
You use the template method patternYou may later add a skeletal abstract class on top
L2

Advanced — Abstraction

Abstract class with state, constructor, and abstract method

  • An abstract class constructor runs for every subclass object, so it is the right place for common setup like ID generation.
  • Concrete methods in the parent can call abstract methods. The subclass version runs at runtime.
abstract class Employee {
    private static int nextId = 1;
    protected final int id;
    protected final String name;

    Employee(String name) {          // runs for every subclass object
        this.id = nextId++;
        this.name = name;
    }

    abstract double monthlyPay();    // HOW is decided by subclasses

    void printPayslip() {            // concrete method calling an abstract one
        System.out.printf("#%d %-6s Rs.%.2f%n", id, name, monthlyPay());
    }
}

class Salaried extends Employee {
    private final double annual;

    Salaried(String name, double annual) {
        super(name);
        this.annual = annual;
    }

    @Override
    double monthlyPay() { return annual / 12; }
}

class Hourly extends Employee {
    private final double rate;
    private final int hours;

    Hourly(String name, double rate, int hours) {
        super(name);
        this.rate = rate;
        this.hours = hours;
    }

    @Override
    double monthlyPay() { return rate * hours; }
}

public class PayrollDemo {
    public static void main(String[] args) {
        Employee[] staff = { new Salaried("Asha", 600000), new Hourly("Ravi", 500, 120) };
        for (Employee e : staff) {
            e.printPayslip();
        }
        // #1 Asha   Rs.50000.00
        // #2 Ravi   Rs.60000.00
    }
}

Template method pattern

  • The abstract class fixes the order of steps in a final method. Subclasses fill in only the steps that change.
  • Real life: making tea and making coffee share boil water and pour into cup, but brewing and extras differ.
  • Optional steps can be "hooks": concrete methods with a default that subclasses may override.
abstract class Beverage {
    final void prepare() {                     // the fixed recipe; cannot be overridden
        boilWater();
        brew();
        pourInCup();
        if (wantsExtras()) {
            addExtras();
        }
    }

    private void boilWater() { System.out.println("Boiling water"); }
    private void pourInCup() { System.out.println("Pouring into cup"); }

    protected abstract void brew();            // step that changes
    protected abstract void addExtras();       // step that changes

    protected boolean wantsExtras() {          // hook with a default
        return true;
    }
}

class Tea extends Beverage {
    @Override protected void brew() { System.out.println("Steeping tea leaves"); }
    @Override protected void addExtras() { System.out.println("Adding milk, sugar, and ginger"); }
}

class BlackCoffee extends Beverage {
    @Override protected void brew() { System.out.println("Dripping coffee through a filter"); }
    @Override protected void addExtras() { }
    @Override protected boolean wantsExtras() { return false; }
}

public class TemplateDemo {
    public static void main(String[] args) {
        new Tea().prepare();
        System.out.println("---");
        new BlackCoffee().prepare();
    }
}

Abstraction in the JDK: program to the interface

  • The JDK is full of abstractions. You call methods on the abstract type; the real class is hidden or replaceable.
  • Declare variables and parameters with the abstract type (List, Map) and choose the concrete class only at new.
Abstraction you useHidden implementations
ListArrayList, LinkedList, immutable lists from List.of
MapHashMap, TreeMap, LinkedHashMap
java.sql.ConnectionMySQL, PostgreSQL, Oracle driver classes
InputStreamFileInputStream, ByteArrayInputStream, network streams
ExecutorServiceThread pools, virtual-thread executors
AbstractList, AbstractMapSkeletal abstract classes that implement most methods for you
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ProgramToInterface {
    static int total(List<Integer> marks) {     // works with ANY List
        int sum = 0;
        for (int m : marks) {
            sum += m;
        }
        return sum;
    }

    public static void main(String[] args) {
        List<Integer> a = new ArrayList<>(List.of(70, 85, 90));
        List<Integer> b = new LinkedList<>(List.of(60, 75));
        System.out.println(total(a)); // 245
        System.out.println(total(b)); // 135
    }
}

Anonymous classes and lambdas for abstract types

  • You cannot write new Greeter() for an abstract class, but you can create an anonymous subclass on the spot.
  • An interface with exactly one abstract method (functional interface) can be implemented with a lambda or method reference.
  • Lambdas work only with interfaces, never with abstract classes.
abstract class Greeter {
    abstract void greet(String name);
}

interface Calculator {
    int apply(int a, int b);                    // one abstract method: functional interface
}

public class AnonymousDemo {
    public static void main(String[] args) {
        Greeter g = new Greeter() {             // anonymous subclass of an abstract class
            @Override
            void greet(String name) { System.out.println("Hello, " + name); }
        };
        g.greet("Asha");

        Calculator add = (a, b) -> a + b;       // lambda
        Calculator max = Math::max;             // method reference
        System.out.println(add.apply(4, 5));    // 9
        System.out.println(max.apply(4, 5));    // 5
        // Greeter bad = name -> System.out.println(name); // ERROR: lambdas need an interface
    }
}

Sealed abstract classes (Java 17+)

  • sealed abstract class Shape permits Circle, Square, Triangle limits which classes may extend the abstraction.
  • Each permitted subclass must be final, sealed, or non-sealed.
  • With Java 21 pattern matching, a switch over a sealed abstract type is checked for completeness by the compiler.
sealed abstract class Shape permits Circle, Square, Triangle {
    abstract double area();
}

final class Circle extends Shape {
    private final double r;
    Circle(double r) { this.r = r; }
    double area() { return Math.PI * r * r; }
}

final class Square extends Shape {
    private final double s;
    Square(double s) { this.s = s; }
    double area() { return s * s; }
}

non-sealed class Triangle extends Shape {
    private final double b, h;
    Triangle(double b, double h) { this.b = b; this.h = h; }
    double area() { return 0.5 * b * h; }
}

public class SealedShapes {
    static String describe(Shape s) {
        return switch (s) {                 // Java 21: exhaustive over permitted types
            case Circle c -> "circle";
            case Square q -> "square";
            case Triangle t -> "triangle";
        };
    }

    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(2), new Triangle(3, 4) };
        for (Shape s : shapes) {
            System.out.printf("%s area = %.2f%n", describe(s), s.area());
        }
    }
}

Interface plus skeletal abstract class

  • Large libraries combine both tools: an interface defines the contract, and an abstract class implements the common parts.
  • Implementers extend the skeleton and write only the unique methods. The JDK does this with List and AbstractList.
interface Shape {
    double area();
    double perimeter();
    String name();
}

abstract class AbstractShape implements Shape {   // shared code written once
    @Override
    public String toString() {
        return String.format("%s: area=%.2f, perimeter=%.2f", name(), area(), perimeter());
    }
}

class Rectangle extends AbstractShape {
    private final double w, h;
    Rectangle(double w, double h) { this.w = w; this.h = h; }
    public double area() { return w * h; }
    public double perimeter() { return 2 * (w + h); }
    public String name() { return "Rectangle"; }
}

public class SkeletalDemo {
    public static void main(String[] args) {
        Shape s = new Rectangle(3, 4);
        System.out.println(s); // Rectangle: area=12.00, perimeter=14.00
    }
}

Abstraction design mistakes

MistakeProblemBetter
Making everything abstract "to be OOP"Extra layers with only one implementationStart concrete; abstract when a second implementation appears
One huge interface with many methodsImplementers write empty methods they do not needSplit into small, focused interfaces
Leaky abstraction: returning internal listsCallers depend on and change internalsReturn copies or read-only views
Calling abstract methods from the constructorSubclass fields are not initialized yetCall them after construction
Checking instanceof on the abstractionDefeats the purpose of abstractionAdd a method to the abstract type instead
Vague names like AbstractManagerHelperImplRole is unclearRole names: Payment, Shape, Repository
L3

Tricky Interview Points

Q1) What is abstraction in Java?

Answer Showing only the essential features of an object and hiding implementation details. Java achieves it with abstract classes and interfaces.

Q2) Give a real-life example of abstraction.

Answer Driving a car: you use the steering, accelerator, and brake without knowing how the engine works. Other examples are a TV remote, an ATM, and a coffee machine.

Q3) How is abstraction achieved in Java?

Answer With abstract classes (partial abstraction, 0 to 100%) and interfaces (a full contract). Access modifiers and packages support it by hiding helpers.

Q4) What is an abstract class?

Answer A class declared with abstract that cannot be instantiated. It can contain abstract and concrete methods, fields, constructors, and static members.

Q5) What is an abstract method?

Answer A method with the abstract keyword and no body, ending with a semicolon. Every concrete subclass must override it.

Q6) Can we create an object of an abstract class?

Answer No. But you can declare a reference of the abstract type pointing to a concrete subclass, or create an anonymous subclass.

Q7) Can an abstract class have a constructor?

Answer Yes. It runs through super(...) when a subclass object is created, usually to initialize common fields.

Q8) Must an abstract class have at least one abstract method?

Answer No. An abstract class with zero abstract methods is legal; it simply cannot be instantiated.

Q9) Can a non-abstract class have an abstract method?

Answer No. If a class declares or inherits an unimplemented abstract method, the class itself must be declared abstract.

Q10) Can an abstract method be private, static, or final?

Answer No. These modifiers prevent overriding, while abstract requires a subclass to override the method. The compiler reports an illegal combination of modifiers.

Q11) Can an abstract class be final?

Answer No. final prevents extending, but an abstract class is useful only when extended.

Q12) Can an abstract class have a main method?

Answer Yes. main is static, so the JVM can run it without creating an object of the abstract class.

Q13) What is the difference between an abstract class and an interface?

Answer An abstract class can have state, constructors, and any access modifiers, but a class can extend only one. An interface has no instance state or constructors, but a class can implement many and it supports lambdas.

Q14) What is the difference between abstraction and encapsulation?

Answer Abstraction hides complexity and shows what an object does. Encapsulation hides data and controls who can change it. Abstraction is a design idea; encapsulation is implemented with private fields and methods.

Q15) Can an interface have method bodies?

Answer Yes, since Java 8 through default and static methods, and since Java 9 through private methods. Abstract methods still have no body.

Q16) Can we use a lambda for an abstract class?

Answer No. Lambdas only implement functional interfaces. For an abstract class you need a named or anonymous subclass.

Q17) What is the template method pattern?

Answer An abstract class defines a final method with the fixed order of steps and leaves some steps abstract for subclasses to implement.

Q18) Is it possible to achieve 100% abstraction with an abstract class?

Answer Yes, if all its methods are abstract, but an interface is the usual choice for a pure contract because a class can implement many interfaces.

L4

Simple Programs

Bank interest rates with an abstract class

abstract class Bank {
    abstract double rateOfInterest();

    double yearlyInterest(double amount) {
        return amount * rateOfInterest() / 100;
    }
}

class Sbi extends Bank {
    @Override double rateOfInterest() { return 6.5; }
}

class Hdfc extends Bank {
    @Override double rateOfInterest() { return 7.0; }
}

class Icici extends Bank {
    @Override double rateOfInterest() { return 7.25; }
}

public class BankDemo {
    public static void main(String[] args) {
        Bank[] banks = { new Sbi(), new Hdfc(), new Icici() };
        for (Bank b : banks) {
            System.out.println(b.getClass().getSimpleName() + ": "
                + b.rateOfInterest() + "% -> Rs." + b.yearlyInterest(100000));
        }
    }
}

Notification sender with an interface

interface Notifier {
    void send(String to, String message);
}

class EmailNotifier implements Notifier {
    public void send(String to, String message) {
        System.out.println("Email to " + to + ": " + message);
    }
}

class SmsNotifier implements Notifier {
    public void send(String to, String message) {
        System.out.println("SMS to " + to + ": " + message);
    }
}

class WhatsAppNotifier implements Notifier {
    public void send(String to, String message) {
        System.out.println("WhatsApp to " + to + ": " + message);
    }
}

public class NotifyDemo {
    static void broadcast(Notifier[] channels, String to, String msg) {
        for (Notifier n : channels) {
            n.send(to, msg);     // caller never knows HOW each channel delivers
        }
    }

    public static void main(String[] args) {
        Notifier[] channels = { new EmailNotifier(), new SmsNotifier(), new WhatsAppNotifier() };
        broadcast(channels, "Asha", "Your order has shipped");
    }
}

ATM: public operations, hidden steps

interface Atm {
    void withdraw(int pin, double amount);
}

class SbiAtm implements Atm {
    private double balance = 10000;
    private static final int PIN = 1234;

    @Override
    public void withdraw(int pin, double amount) {
        if (!verifyPin(pin)) {
            System.out.println("Wrong PIN");
            return;
        }
        if (!hasFunds(amount)) {
            System.out.println("Insufficient balance");
            return;
        }
        balance -= amount;
        dispenseCash(amount);
    }

    private boolean verifyPin(int pin) { return pin == PIN; }          // hidden
    private boolean hasFunds(double amount) { return amount <= balance; } // hidden
    private void dispenseCash(double amount) {                          // hidden
        System.out.println("Please collect Rs." + amount + ". Balance: Rs." + balance);
    }
}

public class AtmDemo {
    public static void main(String[] args) {
        Atm atm = new SbiAtm();      // user sees only withdraw()
        atm.withdraw(1111, 500);     // Wrong PIN
        atm.withdraw(1234, 20000);   // Insufficient balance
        atm.withdraw(1234, 2500);    // Please collect Rs.2500.0. Balance: Rs.7500.0
    }
}

Game template: Cricket and Football

abstract class Game {
    final void play() {
        initialize();
        startPlay();
        endPlay();
    }

    abstract void initialize();
    abstract void startPlay();
    abstract void endPlay();
}

class Cricket extends Game {
    void initialize() { System.out.println("Cricket: toss done, pitch ready"); }
    void startPlay() { System.out.println("Cricket: first ball bowled"); }
    void endPlay() { System.out.println("Cricket: match over after 20 overs"); }
}

class Football extends Game {
    void initialize() { System.out.println("Football: teams on the field"); }
    void startPlay() { System.out.println("Football: kick-off"); }
    void endPlay() { System.out.println("Football: final whistle after 90 minutes"); }
}

public class GameDemo {
    public static void main(String[] args) {
        Game[] games = { new Cricket(), new Football() };
        for (Game g : games) {
            g.play();
            System.out.println();
        }
    }
}

Shapes: abstract class with constructor and concrete method

abstract class Shape {
    private final String color;

    Shape(String color) {
        this.color = color;
    }

    abstract double area();

    void describe() {
        System.out.printf("%s %s, area = %.2f%n", color, getClass().getSimpleName(), area());
    }
}

class Circle extends Shape {
    private final double r;
    Circle(String color, double r) { super(color); this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}

class Rectangle extends Shape {
    private final double w, h;
    Rectangle(String color, double w, double h) { super(color); this.w = w; this.h = h; }
    @Override double area() { return w * h; }
}

class Triangle extends Shape {
    private final double b, h;
    Triangle(String color, double b, double h) { super(color); this.b = b; this.h = h; }
    @Override double area() { return 0.5 * b * h; }
}

public class ShapeDemo {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle("Red", 2), new Rectangle("Blue", 3, 4), new Triangle("Green", 6, 5) };
        for (Shape s : shapes) {
            s.describe();
        }
    }
}

Documents: interface + abstract class together

interface Printable {
    void print();
}

abstract class Document implements Printable {
    protected final String title;

    Document(String title) {
        this.title = title;
    }

    abstract String format();

    @Override
    public void print() {                 // common printing logic
        System.out.println("Printing [" + format() + "] " + title);
    }
}

class PdfDocument extends Document {
    PdfDocument(String title) { super(title); }
    @Override String format() { return "PDF"; }
}

class WordDocument extends Document {
    WordDocument(String title) { super(title); }
    @Override String format() { return "DOCX"; }
}

public class PrintDemo {
    public static void main(String[] args) {
        Printable[] queue = { new PdfDocument("Java Notes"), new WordDocument("Resume") };
        for (Printable p : queue) {
            p.print();
        }
    }
}
L5

Problem Solving Tricks

  • Remember: abstraction = WHAT, implementation = HOW. Abstract methods are the WHAT; subclasses write the HOW.
  • Abstract class = 0 to 100% abstraction; interface = full contract. A class extends one abstract class but implements many interfaces.
  • An abstract method ends with a semicolon and has no braces.
  • abstract never combines with private, static, or final on a method, or with final on a class.
  • Declare variables with the abstract type: List<String> names = new ArrayList<>();.
  • Use an abstract class when subclasses share fields or a constructor; use an interface for a role.
  • Template method: put the fixed algorithm in a final method and leave steps abstract.
  • Lambdas work only with functional interfaces, never with abstract classes.
  • Do not create an abstraction until you have (or clearly expect) two implementations.
  • Name abstractions by role: Payment, Shape, Notifier, not AbstractThingImpl.
L6

Practice Programs List

  1. Create abstract class Vehicle with abstract void start() and implement it in Car, Bike, and Bus.
  2. Write a table of five real-life objects with what the user sees and what is hidden, then code one of them.
  3. Create abstract class Employee with monthlyPay() and subclasses Salaried and Hourly.
  4. Give the abstract class a constructor that stores name, and print it from each subclass.
  5. Try new Employee("x") and write down the exact compiler error.
  6. Try declaring an abstract method as private, static, and final, and record each error.
  7. Write abstract class Bank with rateOfInterest() and three bank subclasses.
  8. Create interface RemoteControl with a default mute() method and implement it for a TV and a fan.
  9. Write the same payment design once with an abstract class and once with an interface. Which fits better and why?
  10. Implement the template method pattern for making tea and coffee.
  11. Create an anonymous subclass of an abstract class inside main.
  12. Write a functional interface Operation and implement add, subtract, and multiply with lambdas.
  13. Create a sealed abstract class Shape with three permitted subclasses and an exhaustive switch.
  14. Write a method total(List<Integer>) and call it with an ArrayList and a LinkedList.