Memra

abstract classes & methods — and final

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.

NORMAL ~/memra/learn/java-from-zero/abstract-and-final utf-8 LF