JavaObject-oriented programmingInheritance and polymorphism

Abstract class

An abstract class is a class declared with the keyword abstract. It represents an abstract concept that is used as a base class for subclasses.

An abstract class has some features:

  • it's impossible to create an instance of an abstract class;
  • it can contain abstract methods which must be implemented in non-abstract subclasses;
  • it also can contain fields and non-abstract methods (including static);
  • an abstract class can extend another class, including abstract;
  • it can contain a constructor.

As you can see, an abstract class has two main differences from regular (concrete) classes: no instances and abstract methods.

Abstract methods are declared by adding the keyword abstract. They have a declaration (modifiers, a return type, and a signature) but don't have an implementation. Each concrete (non-abstract) subclass must implement these methods.

Note, static methods can't be abstract.

Let's see an example. Here is an abstract class Pet:

public abstract class Pet {

    protected String name;
    protected int age;

    protected Pet(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public abstract void say(); // an abstract method
}

The class has two fields, a constructor, and an abstract method.

It's impossible to create instances of this class:

Pet pet = new Pet("Unnamed", 5); // impossible

The method say() is declared abstract because, at this level of abstract, an implementation is not known. Concrete subclasses of the class must implement this method.

Here are two concrete subclasses of Pet, they override the abstract method:

class Cat extends Pet {

    // It can have additional fields as well

    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void say() {
        System.out.println("Meow!");
    }
}

class Dog extends Pet {

    // It can have additional fields as well

    public Dog(String name, int age) {
        super(name, age);
    }

    @Override
    public void say() {
        System.out.println("Wuf!");
    }
}

We can create instances of these classes and call the method say().

Dog dog = new Dog("Boss", 5);
Cat cat = new Cat("Tiger", 2);
        
dog.say(); // it prints "Wuf!"
cat.say(); // it prints "Meow!"

Do not forget, Java doesn't support multiple inheritances for classes. Therefore, a class can extend only one abstract class.

How did you like the theory?
Report a typo