Skip to content

Abstract Classes and Interfaces

Büşra Oğuzoğlu edited this page Jul 18, 2022 · 2 revisions

Abstract Classes:

Abstract classes can not be instantiated (Instances cannot be created using new keyword). For example, it makes sense to make Shape class abstract, because we want circle or rectangle objects, not shape objects. However, we need the Shape class for inheritence and polymorphism. We want our code to be clean and easily understandable.

getArea() and getPerimeter() methods are needed for both Circle and Rectangle objects. So, they can be defined in the Shape super class for simplicity. However, we cannot implement these methods in the Shape class, they should only be declared in the Shape without their implementations if Shape is an abstract class. Therefore, these methods (methods of abstract class, they are only declared, not implemented) are called abstract methods.

In UML diagrams, abstract class names and abstract methods are italicized.

Example of an abstract class:

public abstract class Shape {
    protected String color;
    protected double area;
    protected double perimeter;
    
    // Constructors of abstract classes should be ‘protected’ to prevent instantiation
    protected Shape() {}
    protected Shape(String color) {
        this.color = color;
    }

    // Abstract classes contain abstract methods without method bodies
    protected abstract double getArea();
    protected abstract double getPerimeter();
}

Methods of the abstract class are overriden in child classes. (Denoted by @Override)

Most of the time, we see abstract super classes and concrete subclasses however, it is possible for the superclass to be concrete and child class to be abstract. (All classes that we define are child classes of Java's Object class, it is concrete, but we can define abstract classes like Shape.)

If a class contains an abstract method, it should be defined as abstract. If a subclass of an abstract superclass does not implement all the abstract methods, the subclass must be defined as abstract as well (It inherits abstract methods, therefore it should be abstract if the methods are still abstract). Also, abtsract methods are non-static.

Interfaces:

Clone this wiki locally