intermediate language-deep-dive

Class Inheritance

Inheritance lets a class build on another. The child gets all the parent's properties and methods automatically, can add its own, and can call the parent's constructor with base(). Use it when two things genuinely share structure — not just to reuse code.

Part of: How Clean works

A parent class and a child that extends it:

start:
	Animal cat = Animal("Whiskers", "Meow")
	Dog dog = Dog("Rex", "Labrador")

	print(cat.speak())
	print(dog.speak())
	print(dog.describe())

class Animal
	public:
		string name
		string sound

	constructor(string n, string s)
		name = n
		sound = s

	functions:
		public:
			string speak()
				return name + " says " + sound + "!"

class Dog is Animal
	string breed

	constructor(string n, string b)
		base(n, "Woof")
		breed = b

	functions:
		public:
			string describe()
				return name + " is a " + breed
Whiskers says Meow!
Rex says Woof!
Rex is a Labrador

Dog inherits from Animal with class Dog is Animal. base(n, "Woof") calls Animal's constructor with Rex's name and a hardcoded sound. Dog automatically inherits speak() and accesses the name property — no re-declaration needed. Dog adds its own breed property and describe() method.

A child can override a parent method by defining its own version with the same name:

start:
	Shape s = Shape("grey")
	Circle c = Circle("red", 5.0)

	print(s.info())
	print(c.info())

class Shape
	public:
		string color

	constructor(string c)
		color = c

	functions:
		public:
			string info()
				return "A " + color + " shape"

class Circle is Shape
	number radius

	constructor(string c, number r)
		base(c)
		radius = r

	functions:
		public:
			number area()
				return 3.14159 * radius * radius

			string info()
				return "A " + color + " circle, radius " + radius.toString() + ", area " + area().toString()
A grey shape
A red circle, radius 5, area 78.53975

Circle defines its own info() method, which replaces the parent's version for Circle instances. The color property from Shape is accessible in Circle without re-declaration. This is method overriding — the child provides a more specific version of the parent's behavior.

  • class Child is Parent declares inheritance — Child gets all Parent properties and methods
  • base(args) calls the parent constructor — use it to initialize parent properties
  • Child classes access parent properties by name directly — no re-declaration
  • Define a method with the same name as a parent method to override it
📚 → Book 1, Chapter 6 : Contracts with require →
Copied!