On this page12 sections
Lecture 030: Classes & Objects
| Day | 11: Classes, Objects & Constructors |
| Lecture | 030 of 057 |
| Estimated video length | 14 min |
| Target | Dart 3.12 |
| Level | Beginner |
A car has a brand, a colour and a speed, and it can accelerate. A bank account has an owner and a balance, and you can deposit into it. A class describes a kind of thing: its data and what it can do. An object is one real thing made from that description.
Contents
Prerequisites · Objectives · Lesson · Code Examples · Common Mistakes · Practice Questions · Answers · Takeaways
Prerequisites
Lectures 025–027 (functions and parameters).
Learning Objectives
- Explain the difference between a class and an object
- Define a class with fields and methods
- Create objects and use their fields and methods with
. - Understand that each object keeps its own data
- Check an object's type with
isandruntimeType
1. Class: Blueprint, Object: The Real Thing
A class is like the plan for a house; the houses built from it are the objects. One plan, many houses, each with its own furniture.
| Term | Meaning | Example |
|---|---|---|
| class | the description of a kind of thing | Car |
| object / instance | one thing made from the class | car1, car2 |
| field | a variable that belongs to the object | brand, speed |
| method | a function that belongs to the object | accelerate() |
2. Defining a Class
class Car {
String brand = '';
String color = '';
int speed = 0;
void accelerate(int amount) {
speed += amount;
print('$brand is now going $speed km/h');
}
void describe() {
print('A $color $brand');
}
}- Class names start with a capital letter:
Car,BankAccount. - Fields hold the data. Here each field starts with a value (
'',0). - Methods are written like functions, and can use the fields directly.
Classes are written outside main, at the top level of the file.
3. Creating and Using Objects
Call the class name like a function to create an object. Use . to reach its fields and methods:
void main() {
var car1 = Car();
car1.brand = 'Toyota';
car1.color = 'white';
car1.describe();
car1.accelerate(40);
car1.accelerate(20);
}Output
A white Toyota
Toyota is now going 40 km/h
Toyota is now going 60 km/h4. Every Object Has Its Own Data
var car2 = Car();
car2.brand = 'Honda';
car2.color = 'red';
car2.describe(); // A red Honda
print(car1.speed); // 60
print(car2.speed); // 0Speeding up car1 didn't touch car2. Same class, separate objects.
5. Checking the Type
print(car1 is Car); // true
print(car1.runtimeType); // Car
print(car1); // Instance of 'Car'The class is also a type: you can write Car myCar = Car(); just like int x = 5;.
Code Examples
Example 1: Two Bank Accounts
class BankAccount {
String owner = '';
double balance = 0;
void deposit(double amount) {
balance += amount;
print('$owner deposited Rs $amount. Balance: Rs $balance');
}
void withdraw(double amount) {
if (amount > balance) {
print('$owner: not enough balance for Rs $amount');
return;
}
balance -= amount;
print('$owner withdrew Rs $amount. Balance: Rs $balance');
}
}
void main() {
var a = BankAccount();
a.owner = 'Ayesha';
var b = BankAccount();
b.owner = 'Usman';
a.deposit(5000);
b.deposit(1200);
a.withdraw(2000);
b.withdraw(3000);
print('Final: ${a.owner} Rs ${a.balance}, ${b.owner} Rs ${b.balance}');
}Output
Ayesha deposited Rs 5000.0. Balance: Rs 5000.0
Usman deposited Rs 1200.0. Balance: Rs 1200.0
Ayesha withdrew Rs 2000.0. Balance: Rs 3000.0
Usman: not enough balance for Rs 3000.0
Final: Ayesha Rs 3000.0, Usman Rs 1200.0The deposit and withdraw rules are written once, in the class, and every account follows them.
Common Beginner Mistakes
1. A field with no value
class Car {
String brand;
}Error: Field 'brand' should be initialized because its type 'String' doesn't allow null.Give it a starting value (String brand = '';), make it nullable (String? brand;), or set it in
a constructor (Lecture 031).
2. Calling a method the class doesn't have
var c = Car();
c.drive();Error: The method 'drive' isn't defined for the type 'Car'.3. Using the class instead of an object
Car.brand = 'Toyota';Error: Setter not found: 'brand'.Fields belong to objects. Create one first: var c = Car(); c.brand = 'Toyota';.
4. Lowercase class names: class car works, but Dart style is UpperCamelCase for classes
and lowerCamelCase for variables.
Practice Questions
- What's the difference between a class and an object?
- Write a class
Dogwith anamefield (default'') and abark()method that prints<name> says Woof!. - Create a
DogcalledTommyand make it bark. - If two
Carobjects are created and one accelerates, does the other's speed change? - What does
print(car1)show for a class that doesn't overridetoString()?
Practice Answers
- A class describes a kind of thing; an object is one actual thing made from it.
class Dog {
String name = '';
void bark() {
print('$name says Woof!');
}
}var d = Dog(); d.name = 'Tommy'; d.bark();- No. Each object has its own fields.
Instance of 'Car'. (Lecture 043 shows how to change that.)
Key Takeaways
- A class bundles data (fields) and behaviour (methods).
- An object is made from a class:
var car = Car();. - Use
.to read fields and call methods:car.speed,car.accelerate(10). - Each object keeps its own field values.
- Class names start with a capital letter.