Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Java reference

abstract

Marks a class that cannot be instantiated and a method without a body that subclasses implement.

Available since: Java 1.0

Syntax

abstract class Name { abstract Type method(); }

Examples

Shared logic in the abstract class, details in subclasses:

abstract class Employee {
    String name;
 
    Employee(String name) {
        this.name = name;
    }
 
    abstract double salary();
 
    String payslip() {
        return name + ": " + salary();
    }
}
 
class Manager extends Employee {
    Manager(String name) { super(name); }
    double salary() { return 5000; }
}
 
void main() {
    Employee e = new Manager("Anna");
    IO.println(e.payslip());
    // new Employee("Oleg");  // error: Main.Employee is abstract; cannot be instantiated
}

Output:

Anna: 5000.0

Notes

An abstract class can have fields, constructors and regular methods; an interface cannot (except constants). A subclass that does not implement all abstract methods must be abstract too.

See also

  • interface — Declares an interface — a set of methods that a class promises to implement.
  • extends — Declares inheritance: the class gets the parent's fields and methods.
  • super — Refers to the parent class: calls its constructor or its version of a method.

In the tutorial

  • Abstract classes — Abstract classes and methods in Java: the abstract keyword, shared code for subclasses and why such classes cannot be instantiated.

Thanks for reading!

Donate to the site — we work hard for you.