Skip to content

Abstract classes (course memo)

Java. An abstract class describes a general idea and is deliberately unfinished — you can't instantiate it with new. Instead, you extend it into a concrete class that can be instantiated. Every subclass shares whatever non-private code the abstract class defines.

Abstract classes

java
public abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}
  • abstract before class — can no longer be created with new.
  • Extended (extends) as normal.
java
public class Dog extends Animal {
    private int lovePoints;

    public Dog(String name, int lovePoints) {
        super(name);
        this.lovePoints = lovePoints;
    }

    public int getLovePoints() {
        return lovePoints;
    }
}
  • Dog (concrete) can be instantiated; Animal (abstract) can't.
  • Just like with interfaces, a Dog can go into a List<Animal>.

Abstract methods

java
public abstract class Animal {
    private String name;

    public Animal(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public abstract String move();
}
  • abstract before the return type marks the method itself as unfinished — no body.
  • Every concrete subclass must implement it.
  • An abstract method can't be private (a private method couldn't be overridden by a subclass anyway).
java
public class Dog extends Animal {
    public Dog(String name) { super(name); }

    @Override
    public String move() { return "The dog walks"; }
}

public class Bird extends Animal {
    public Bird(String name) { super(name); }

    @Override
    public String move() { return "The bird flies"; }
}

Interfaces vs abstract classes

Both can force implementations to have specific methods. Beyond that:

Can doInterfaceAbstract class
Force specific methodsyesyes
Share static properties (Java 8+)yes
Share default/implemented methods (Java 8+)yes
Share (instance) properties/fieldsnoyes
Share implemented (instance) methodslimited (default methods)yes

(See 16-interfaces-advanced.md for what interfaces gained in Java 8.)