Back to quest
Object Oriented ProgrammingLevel 24 / 32

Classes & Objects

Introduction to Object-Oriented Programming (OOP) in Dart. Learn how to define classes and create objects.

Dart is an object-oriented language. Everything is an object. Classes are the blueprints for creating these objects.

1. What is a Class?

A class is a custom data type that bundles data (fields) and behavior (methods) together.

Defining a Class

example.dart
1class Person {
2 // Fields (Data)
3 String name = 'Unknown';
4 int age = 0;
5 
6 // Method (Behavior)
7 void introduce() {
8 print('Hi, my name is $name and I am $age years old.');
9 }
10}

HintThis Person class is a template. It describes what a person "has" and "does".

2. Creating Objects

An object is an instance of a class. You create it by calling the class name like a function.

Instantiating

example.dart
1void main() {
2 // Create an object
3 Person p1 = Person();
4
5 // Modify its fields
6 p1.name = 'Alice';
7 p1.age = 30;
8
9 // Call its method
10 p1.introduce(); // Hi, my name is Alice and I am 30 years old.
11}

Hintp1 is a specific person object created from the Person blueprint.

3. Why OOP?

OOP helps organize complex code by modeling real-world things. Instead of loose variables, you have structured objects.

Without vs With Classes

example.dart
1// Without Classes (Messy)
2String name1 = 'Alice';
3int age1 = 30;
4String name2 = 'Bob';
5int age2 = 25;
6 
7// With Classes (Organized)
8Person p1 = Person(); // Alice's data inside p1
9Person p2 = Person(); // Bob's data inside p2

HintClasses keep related data packaged together.

Loot collected

Key takeaways
  • A Class is a blueprint; an Object is one instance of that blueprint.
  • Fields store data (state); Methods perform actions (behavior).
  • Use dot notation (object.field) to access members.
  • Dart classes effectively allow you to create your own custom types.

Side quests

Practice exercises

1

Exercise 1: Create a Class

Create a Car class with fields brand and speed. Add a drive() method.

Reveal solution
solution.dart
1class Car { String brand = 'Toyota'; int speed = 0; void drive() { print('Vroom'); } }
2

Exercise 2: Use the Class

Create a Car object, set its brand to "Tesla", and call drive().

Reveal solution
solution.dart
1Car c = Car(); c.brand = 'Tesla'; c.drive();
Party chat

Comments