Start learning free

LESSON 639 OF 671 · OBJECT-ORIENTED PROGRAMMING

Abstract Classes in Go

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. Go has no abstract classes; an interface plays that role.


// Animal is an interface — a value of it always holds some concrete type
type Animal interface {
    speak()
}

type Dog struct{}

func (d Dog) speak() { fmt.Println("Woof") }


Full lesson:

Sometimes you want to capture shared behavior across a family of types 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 interfaces are for.

Two superpowers

  1. You can't use Animal as a concrete type directly — you have to provide a concrete struct that satisfies the interface.
  2. Any struct assigned to an Animal variable MUST implement every method of the interface, or the compiler complains. The interface is a contract with teeth.

Mixing abstract and concrete

In Go, interfaces declare only method signatures — there are no concrete fields or default method bodies inside an interface. Shared behavior lives in the structs that implement the interface. Only the methods declared in the interface require an implementation.

Notes by language

  • Go — no abstract keyword; an interface lists the required methods, and any type that has them satisfies it.
  • C# / Java — keyword abstract on the class and on the method.
  • Python — inherit from abc.ABC and decorate the method with @abstractmethod.
  • JavaScript — no built-in support. The convention is a parent class whose method throws an error if not overridden.
  • C++ — a method ending with = 0 is "pure virtual"; a class with any pure virtual method is abstract.

Your task

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

Expected output:

Woof
STEP 1 OF 3
    Ctrl + Enter to check