Start learning free

LESSON 645 OF 677 · OBJECT-ORIENTED PROGRAMMING

Abstract Classes in Scala

Lesson

TL ; DR:

An abstract class is a class you can't instantiate directly — it's a half-finished template. It can declare methods with no body (abstract methods) that any concrete subclass must implement.


abstract class Animal {
    def speak(): Unit   // no body — concrete
                        // subclasses must provide one
}
class Dog extends Animal {
    override def speak(): Unit = {
        println("Woof")
    }
}


Full lesson:

Sometimes you want to capture shared behavior across a family of classes without committing to one concrete implementation. For example, every Animal can speak(), but exactly how depends on whether it's a Dog or a Cat. That's what abstract classes are for.

Two superpowers

  1. You can't write new Animal() directly — the compiler stops you (Animal is abstract; it cannot be instantiated). You have to pick a concrete subclass.
  2. Any subclass MUST implement every abstract method, or the compiler complains. The abstract class is a contract with teeth.

Mixing abstract and concrete

An abstract class can also have concrete methods (with bodies) and fields. Those are shared by all subclasses for free, just like normal inheritance. Only the methods marked abstract require an override.

Notes by language

  • C# / Java — keyword abstract on the class and on the method.
  • Python — inherit from abc.ABC and decorate the method with @abstractmethod.
  • Scala — keyword abstract on the class; a method with no body is abstract, and the subclass implements it with override def.
  • C++ — a method ending with = 0 is "pure virtual"; a class with any pure virtual method is abstract.

Your task

The abstract Animal class is already defined. Create a concrete Dog subclass and implement the speak method so it prints "Woof". The harness builds a Dog and calls speak().

Expected output:

Woof
STEP 1 OF 2
    Ctrl + Enter to check