An abstract class is a partial implementation: it can hold state, constructors and concrete methods, but leaves some methods for subclasses to fill in.
Rules
A class with at least one abstract method must be declared
abstract(an abstract class may also have none).It can have constructors (called via
super(...)), instance fields, static members,finalandprivatemethods.A concrete subclass must implement all inherited abstract methods, or be
abstractitself.abstractcan't be combined withfinal,staticorprivateon a method — those can't be overridden.
abstract class Shape {
abstract double area();
}
public class Main {
public static void main(String[] args) {
Shape s = new Shape();
}
}Main.java:7: error: Shape is abstract; cannot be instantiated
Shape s = new Shape();
^Template method pattern
The abstract class fixes the algorithm skeleton in a final method and lets subclasses supply the varying steps.
public class Main {
public static void main(String[] args) {
new CsvReport().generate();
new JsonReport().generate();
}
}
abstract class Report {
private final String title;
protected Report(String title) { this.title = title; } // abstract classes have constructors
// template method: fixed order, cannot be overridden
public final void generate() {
System.out.println("== " + title + " ==");
System.out.println(header());
System.out.println(body());
footer();
}
protected abstract String header(); // required steps
protected abstract String body();
protected void footer() { System.out.println("-- end --"); } // optional hook
}
class CsvReport extends Report {
CsvReport() { super("CSV"); }
@Override protected String header() { return "name,score"; }
@Override protected String body() { return "asha,91"; }
}
class JsonReport extends Report {
JsonReport() { super("JSON"); }
@Override protected String header() { return "{"; }
@Override protected String body() { return " \"asha\": 91\n}"; }
@Override protected void footer() { } // override the hook
}== CSV ==
name,score
asha,91
-- end --
== JSON ==
{
"asha": 91
}Anonymous subclass of an abstract class
public class Main {
public static void main(String[] args) {
Greeter g = new Greeter("Asha") { // anonymous concrete subclass
@Override String greeting() { return "Namaste"; }
};
System.out.println(g.greet());
}
}
abstract class Greeter {
private final String name;
Greeter(String name) { this.name = name; }
abstract String greeting();
String greet() { return greeting() + ", " + name + "!"; }
}Namaste, Asha!When to choose an abstract class
Can an abstract class have a constructor? Why?
Can an abstract class have no abstract methods?
Can an abstract method be private, static or final?