beginner first-steps

Classes: Grouping Data and Behavior

Functions let you reuse code. Classes let you group related data and functions together. Think of a class as a blueprint — define what something looks like and what it can do, then create as many instances as you need.

Part of: Install and setup

start:
	Person alice = Person("Alice", 28)
	Person bob = Person("Bob", 35)

	print(alice.introduce())
	print(bob.introduce())
	print(alice.name)

class Person
	integer age

	public:
		string name

	constructor(string personName, integer personAge)
		name = personName
		age = personAge

	functions:
		public:
			string introduce()
				return "Hi, I'm {name} and I'm {age} years old."
Hi, I'm Alice and I'm 28 years old.
Hi, I'm Bob and I'm 35 years old.
Alice

The constructor runs when you create a new instance and sets up the initial values. Access fields and methods with dot notation — alice.name, alice.introduce(). Members are private unless they are listed under public:, which is why name and introduce() sit there.

Classes can build on each other using inheritance:

start:
	Dog rex = Dog("Rex", "Labrador")
	print(rex.describe())
	print(rex.name)

class Animal
	public:
		string name

	constructor(string animalName)
		name = animalName

	functions:
		public:
			string describe()
				return "I am {name}."

class Dog is Animal
	string breed

	constructor(string dogName, string dogBreed)
		base(dogName)
		breed = dogBreed

	functions:
		public:
			string describe()
				return "I am {name}, a {breed}."
I am Rex, a Labrador.
Rex

Dog is Animal means Dog gets everything Animal has. base(dogName) calls the parent constructor. Then Dog adds its own breed field and overrides describe().

  • A class groups related fields (data) and functions (behavior) together
  • constructor(params) runs when you create a new instance
  • Access fields and methods with dot notation: alice.name, alice.introduce()
  • class Dog is Animal — Dog inherits everything from Animal
  • base(args) calls the parent constructor — required when using inheritance
  • Override a method by declaring it again in the child class
📚 → Book 1, Chapters 21–23 : Handling Errors →
Copied!