Video in progress

What is an abstract class, and can you create an object from it directly?

An abstract class is an incomplete class marked abstract: it may contain abstract methods without a body. You can't create an object from it with new; objects come only from a concrete child class that extends it.

📖 Answer

public abstract class Report {
    // the shared algorithm, the same for every report
    public final byte[] generate() {
        var rows = loadData();
        return render(rows);
    }

    protected abstract List<String[]> loadData();     // the child writes this
    protected abstract byte[] render(List<String[]> rows);
}

public class SalesCsvReport extends Report {
    @Override protected List<String[]> loadData() { /* ... */ return List.of(); }
    @Override protected byte[] render(List<String[]> rows) { /* CSV */ return new byte[0]; }
}

// new Report();            // compile error
Report r = new SalesCsvReport();   // correct

A few more things to know:

  • it can have a constructor, regular fields and full methods;
  • you can make a class abstract even without any abstract method, just so that no objects get created;
  • if a child class doesn't implement all the abstract methods, it must be abstract itself;
  • you can create an "object" through an anonymous class: new Report() { ... }, but that is really a nameless child class.