Skip to lesson

Abstract classes and abstract methods

Some ideas are too general to be real objects: you can draw a rectangle or a triangle, but not a plain "shape". Java marks such a class abstract, so it can be a parent but never an object.

An abstract class: a parent you cannot create

An abstract class is a class declared with the abstract keyword that cannot be instantiated with new. It is meant to be a parent: it holds what its children share and can declare abstract methods that they must write.

A drawing app has rectangles and triangles, and both are shapes. Write abstract class Shape, and Java stops anyone from writing new Shape(). Shape can still be the type of a variable.

Example 1 · The smallest abstract class

ShapeDemo.javaJava
abstract class Shape {    abstract double area();}
class Rectangle extends Shape {    double width, height;
    Rectangle(double width, double height) {        this.width = width;        this.height = height;    }
    @Override    double area() {        return width * height;    }}
class Triangle extends Shape {    double base, height;
    Triangle(double base, double height) {        this.base = base;        this.height = height;    }
    @Override    double area() {        return 0.5 * base * height;    }}
public class ShapeDemo {    public static void main(String[] args) {        Shape s1 = new Rectangle(4, 5);        Shape s2 = new Triangle(6, 4);        System.out.println("Rectangle: " + s1.area());        System.out.println("Triangle: " + s2.area());    }}
Output
Rectangle: 20.0
Triangle: 12.0

What this code does

  • Shape is abstract, so it is only a parent. abstract double area(); has no body: each child writes its own area.
  • The variables have the abstract type Shape, but each object is a real child, so the right area runs.

Example 2 · Mistake: new on an abstract class

NewShapeDemo.javaJava
abstract class Shape {    abstract double area();}
public class NewShapeDemo {    public static void main(String[] args) {        Shape s = new Shape();        System.out.println(s.area());    }}
Sample compiler output
NewShapeDemo.java:7: error: Shape is abstract; cannot be instantiated
        Shape s = new Shape();
                  ^
1 error

What this code does

  • An abstract class is only a parent. A plain "shape" has no area to work out, so Java refuses to create one.
  • Fix: create a concrete child, like new Rectangle(4, 5), and keep the Shape variable if you like.

To instantiate means to create an object with new. Shape s = new Rectangle(4, 5); is fine: the variable has the abstract type, and the object is a real child.

Abstract methods: a rule with no body

An abstract method is a method declared with abstract that has a header but no body, ending in a semicolon, as in abstract double area();. Every concrete child class must write a body for it.

A plain shape has no formula for its area. So Shape declares abstract double area(); with a semicolon instead of braces. It says "every shape has an area" without pretending to know how.

Example 3 · Mistake: braces in the wrong place

ExamBodyDemo.javaJava
abstract class Exam {    abstract int maxMarks() {        return 100;    }
    int passMarks();}
public class ExamBodyDemo {    public static void main(String[] args) {        System.out.println("Exam app");    }}
Sample compiler output
ExamBodyDemo.java:2: error: abstract methods cannot have a body
    abstract int maxMarks() {
                 ^
ExamBodyDemo.java:6: error: missing method body, or declare abstract
    int passMarks();
        ^
2 errors

What this code does

  • maxMarks is abstract but has a body. Remove the braces and end it with ;, or remove abstract.
  • passMarks is a normal method with no body. Add braces with code, or mark it abstract.

Only an abstract class may hold abstract methods. If a normal class has one, javac says the class is not abstract and does not override abstract method, naming the class itself.

Concrete classes keep the promise

A concrete class is a class that is not abstract, so objects of it can be created with new. It must have a body for every method, including each abstract method it inherits. A method with a body is a concrete method.

A concrete child must implement (write a body for) every abstract method it inherits. If Circle forgets area(), javac stops it, so the dummy-body bug from Why abstraction? (opens in a new tab) can no longer happen.

Example 4 · Mistake: a child forgets an abstract method

ForgotDemo.javaJava
abstract class Shape {    abstract double area();}
class Circle extends Shape {    double radius;}
public class ForgotDemo {    public static void main(String[] args) {        Shape c = new Circle();        System.out.println(c.area());    }}
Sample compiler output
ForgotDemo.java:5: error: Circle is not abstract and does not override abstract method area() in Shape
class Circle extends Shape {
^
1 error

What this code does

  • Circle is a concrete class but has no area. javac points at the class and names the missing method.
  • Compare with the dummy-body version in the last lesson: that one ran silently, this one cannot even compile.
  • Fix: add @Override double area() { return 3.14 * radius * radius; } to Circle.

Example 5 · An abstract child passes the job down

VehicleDemo.javaJava
abstract class Vehicle {    abstract int wheels();    abstract String fuel();}
abstract class TwoWheeler extends Vehicle {    @Override    int wheels() {        return 2;    }}
class Scooter extends TwoWheeler {    @Override    String fuel() {        return "Petrol";    }}
class EBike extends TwoWheeler {    @Override    String fuel() {        return "Battery";    }}
public class VehicleDemo {    public static void main(String[] args) {        Vehicle v1 = new Scooter();        Vehicle v2 = new EBike();        System.out.println("Scooter: " + v1.wheels() + " wheels, " + v1.fuel());        System.out.println("EBike: " + v2.wheels() + " wheels, " + v2.fuel());    }}
Output
Scooter: 2 wheels, Petrol
EBike: 2 wheels, Battery

What this code does

  • TwoWheeler implements only wheels, so it must stay abstract. It passes fuel down to its children.
  • Scooter and EBike are concrete, so between them and their parents every abstract method now has a body.

Implementing is overriding, so the rules from Method overriding (opens in a new tab) apply: same name and parameters, same or wider access, and @Override as a habit. A child may also stay abstract: it implements some methods and passes the rest down to its own children.

An abstract type for variables and arrays

A company pays full-time staff, interns and contract workers in different ways. An Employee[] array holds all three. The loop calls each object's own monthlyPay(), and every element is sure to have a real one.

Example 6 · A payroll with an abstract parent array

PayrollDemo.javaJava
abstract class Employee {    abstract String name();    abstract int monthlyPay();}
class FullTime extends Employee {    @Override    String name() { return "Kavya (full-time)"; }
    @Override    int monthlyPay() { return 50000; }}
class Intern extends Employee {    @Override    String name() { return "Rohan (intern)"; }
    @Override    int monthlyPay() { return 15000; }}
class Contract extends Employee {    int hours = 120;    int rate = 300;
    @Override    String name() { return "Arjun (contract)"; }
    @Override    int monthlyPay() { return hours * rate; }}
public class PayrollDemo {    public static void main(String[] args) {        Employee[] staff = { new FullTime(), new Intern(), new Contract() };        int total = 0;        for (Employee e : staff) {            System.out.println(e.name() + ": Rs. " + e.monthlyPay());            total = total + e.monthlyPay();        }        System.out.println("Total: Rs. " + total);    }}
Output
Kavya (full-time): Rs. 50000
Rohan (intern): Rs. 15000
Arjun (contract): Rs. 36000
Total: Rs. 101000

What this code does

  • The loop treats every object as an Employee and calls monthlyPay. Each object runs its own version.
  • Every element is a concrete child, so every call has a real body behind it. Adding a new employee type means one new class, and the loop does not change.

This is the dispatch from Dynamic method dispatch (opens in a new tab), now with a guarantee. An array of an abstract type is allowed, because each element is a concrete child; nothing can fall back to a fake body.

Rules and traps

javac checks four more rules, and breaking one stops the program from compiling. Each snippet below breaks one: tap the wrong line, then read the real error and the fix.

The rules in one place:

  • An abstract class may have zero abstract methods, and it still cannot be instantiated.
  • A class with even one abstract method must be declared abstract.
  • An abstract method cannot be private, static or final: a child could never override it.
  • A class cannot be both abstract and final: one needs children, the other forbids them.

Find the bug

Find the abstract mistake

Select the line that is wrong.

Every exam type must say its own maximum marks.

Round 1 of 4

Next step

Check your understanding

12 quick questions