Java Abstract Classes

An abstract class is a class which you can not create objects of. It is made to be a base for other classes. It can have abstract methods (no body, only the name) which the subclasses must write, and also normal methods with code.

Example

abstract class Employee {
    String name;

    Employee(String name) {
        this.name = name;
    }

    abstract double salary();            // no body: every subclass must write it

    void show() {                        // a normal method
        System.out.println(name + " earns " + salary());
    }
}

class FullTime extends Employee {
    double monthly;
    FullTime(String name, double monthly) { super(name); this.monthly = monthly; }

    @Override
    double salary() { return monthly; }
}

class Freelancer extends Employee {
    double hourly; int hours;
    Freelancer(String name, double hourly, int hours) { super(name); this.hourly = hourly; this.hours = hours; }

    @Override
    double salary() { return hourly * hours; }
}

public class Main {
    public static void main(String[] args) {
        Employee[] team = { new FullTime("Riya", 60000), new Freelancer("Aman", 500, 40) };
        for (Employee e : team) {
            e.show();
        }
    }
}
Output

Riya earns 60000.0
Aman earns 20000.0

You can not create an object

abstract class Shape {
    abstract double area();
}

public class NoObject {
    public static void main(String[] args) {
        Shape s = new Shape();
    }
}
Output

NoObject.java:7: error: Shape is abstract; cannot be instantiated
Shape s = new Shape();
^
1 error
error: compilation failed

A subclass must implement all abstract methods

abstract class Shape {
    abstract double area();
}

class Square extends Shape {
    // forgot to write area()
}

public class Forgot {
    public static void main(String[] args) { }
}
Output

Forgot.java:5: error: Square is not abstract and does not override abstract method area() in Shape
class Square extends Shape {
^
1 error
error: compilation failed

Template method pattern

A very useful use of abstract classes: the parent defines the steps, and the children fill the details.

abstract class Report {
    final void print() {                 // the fixed steps
        System.out.println("--- " + title() + " ---");
        System.out.println(body());
        System.out.println("--- end ---");
    }

    abstract String title();
    abstract String body();
}

class SalesReport extends Report {
    String title() { return "Sales"; }
    String body() { return "Total: 120 items"; }
}

public class Template {
    public static void main(String[] args) {
        new SalesReport().print();
    }
}
Output

— Sales —
Total: 120 items
— end —

Facts

  • An abstract class can have constructors, fields and normal methods.
  • A class with even one abstract method must be declared abstract.
  • An abstract method can not be private, static or final.

Abstract class or interface?

PointAbstract classInterface
Inherit fromOnly one classMany interfaces
State (fields)Can have instance fieldsOnly constants
Use whenRelated classes share code and stateDifferent classes share a behavior
Note: Next we see interfaces, which are the other way to define a contract. Next: Java Interfaces.

Congratulations! Chapter Finished. Learn more about the similar topics:
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.