Course contentsShow
← Computer Science
Lesson 2128 of 2,87248. Programming ParadigmsFree lesson

Abstract Classes and Interfaces

Define abstract classes with incomplete implementations and interfaces as pure contracts that classes must implement.

Abstract Classes and Interfaces

What you'll learn: How abstract classes and interfaces let you define contracts and partial implementations that other classes must fulfill.

Core Idea

In object-oriented programming, sometimes you want to define what a class should do without fully specifying how it does it. Abstract classes let you create partially implemented blueprints—they can have some complete methods and some incomplete ones (called abstract methods) that subclasses must implement. Interfaces are pure contracts with no implementation at all; they just declare method signatures that any implementing class must provide.

Abstract Classes

Think of an abstract class like a template with blanks. You might define a Shape abstract class with a concrete method getColor() (fully implemented) but an abstract method calculateArea() (no implementation). Any class inheriting from Shape must fill in the calculateArea() method:

abstract class Shape {
    color
    
    getColor() { return color }
    
    abstract calculateArea()  // no body!
}

class Circle extends Shape {
    radius
    
    calculateArea() { return 3.14 * radius * radius }
}

Interfaces

Interfaces are even stricter—they define only method signatures with zero implementation. They describe what behaviors a class promises to support:

interface Drawable {
    draw()
    erase()
}

class Button implements Drawable {
    draw() { /* render button */ }
    erase() { /* clear button */ }
}

Multiple classes can implement the same interface in completely different ways, ensuring they all speak the same "language."

Why Use Them?

Abstract classes share common code among related classes while enforcing certain methods. Interfaces enforce consistency across unrelated classes, enabling polymorphism—you can treat any Drawable the same way without knowing its specific type.

Key Takeaway: Abstract classes provide partial implementations with required overrides; interfaces define pure contracts that classes must fulfill, both enabling flexible, maintainable object-oriented designs.