Memra

abstract classes & methods — and final

◈ 4 cards

abstract forces subclasses to implement; final prevents extension or override.

abstract — defining a contract without an implementation

An abstract class cannot be instantiated directly; it exists to be extended:

public abstract class Shape {
    abstract double area();          // no body — subclass must provide one
    void printArea() {               // concrete method — inherited as-is
        System.out.println("Area: " + area());
    }
}

public class Circle extends Shape {
    double radius;
    Circle(double r) { this.radius = r; }
    @Override
    double area() { return Math.PI * radius * radius; }  // must implement
}

Rules for abstract: - A class with any abstract method must be declared abstract. - A concrete subclass must implement all inherited abstract methods, or itself be declared abstract. - new Shape() is a compile error — you cannot instantiate an abstract class.

final — closing the door on extension

  • final class — cannot be extended. String, Integer, all wrapper types, and Math are final.
  • final method — cannot be overridden (but the class can still be extended).
  • A class cannot be both abstract and final — that would be a class that cannot be instantiated or extended, making it unusable.
declarationcompiles?whynew Shape()noabstract — no instancesclass Circle extends Shape{ }noarea() still has no bodyabstract final class Shapenothe two cancel outfinal void lock() in Baseyesonly the method is sealed
abstract means “must be extended”, final means “cannot be” — which is why the pair cancels out. A concrete subclass owes a body for every abstract method it inherits.
NORMAL ~/memra/learn/java-from-zero/abstract-and-final utf-8 LF