On this page12 sections
  1. Prerequisites
  2. Learning Objectives
  3. 1. Class: Blueprint, Object: The Real Thing
  4. 2. Defining a Class
  5. 3. Creating and Using Objects
  6. 4. Every Object Has Its Own Data
  7. 5. Checking the Type
  8. Code Examples
  9. Common Beginner Mistakes
  10. Practice Questions
  11. Practice Answers
  12. Key Takeaways

Lecture 030: Classes & Objects

Day11: Classes, Objects & Constructors
Lecture030 of 057
Estimated video length14 min
TargetDart 3.12
LevelBeginner

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 is and runtimeType

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.

TermMeaningExample
classthe description of a kind of thingCar
object / instanceone thing made from the classcar1, car2
fielda variable that belongs to the objectbrand, speed
methoda function that belongs to the objectaccelerate()

2. Defining a Class

dart
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:

dart
void main() {
  var car1 = Car();
  car1.brand = 'Toyota';
  car1.color = 'white';
  car1.describe();
  car1.accelerate(40);
  car1.accelerate(20);
}

Output

code
A white Toyota
Toyota is now going 40 km/h
Toyota is now going 60 km/h

4. Every Object Has Its Own Data

dart
var car2 = Car();
car2.brand = 'Honda';
car2.color = 'red';
car2.describe();     // A red Honda

print(car1.speed);   // 60
print(car2.speed);   // 0

Speeding up car1 didn't touch car2. Same class, separate objects.

5. Checking the Type

dart
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

dart
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

code
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.0

The deposit and withdraw rules are written once, in the class, and every account follows them.


Common Beginner Mistakes

1. A field with no value

dart
class Car {
  String brand;
}
code
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

dart
var c = Car();
c.drive();
code
Error: The method 'drive' isn't defined for the type 'Car'.

3. Using the class instead of an object

dart
Car.brand = 'Toyota';
code
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

  1. What's the difference between a class and an object?
  2. Write a class Dog with a name field (default '') and a bark() method that prints <name> says Woof!.
  3. Create a Dog called Tommy and make it bark.
  4. If two Car objects are created and one accelerates, does the other's speed change?
  5. What does print(car1) show for a class that doesn't override toString()?

Practice Answers

  1. A class describes a kind of thing; an object is one actual thing made from it.
dart
class Dog {
  String name = '';

  void bark() {
    print('$name says Woof!');
  }
}
  1. var d = Dog(); d.name = 'Tommy'; d.bark();
  2. No. Each object has its own fields.
  3. 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.