Menu
Coddy logo textTech

Classes vs Objects

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 4 of 110.

Classes and objects serve different purposes. A class is a blueprint, while an object is what you build from that blueprint.

Here is an example of a class with instance variables:

class Dog {
  String name = '';
  String breed = '';
}

The variables declared inside a class (like name and breed) belong to each object created from that class. We will explore instance variables in depth later.

Create multiple objects from the same class:

Dog dog1 = Dog();
Dog dog2 = Dog();

Each object can have its own unique values for those variables:

dog1.name = 'Nicky';
dog1.breed = 'Siberian Husky';

dog2.name = 'Teemon';
dog2.breed = 'Labrador';

Use the dot operator . to access an object's variables:

print('${dog1.name} is a ${dog1.breed}');
print('${dog2.name} is a ${dog2.breed}');

Output:

Nicky is a Siberian Husky
Teemon is a Labrador

Key Difference: The class Dog defines the structure all dogs share, while dog1 and dog2 are individual objects with their own unique data.

challenge icon

Challenge

Easy

Complete the code to create two student objects from the Student class and set their variables.

  • student.dart: Contains the Student class (locked)
  • driver.dart: Create two objects and set their data

Set the following values:

  • student1: name is 'Alice' with grade 'A'
  • student2: name is 'Bob' with grade 'B'

Cheat sheet

A class is a blueprint that defines the structure and behavior of objects. An object is an instance created from a class.

Define a class with instance variables:

class Dog {
  String name = '';
  String breed = '';
}

Create objects from a class:

Dog dog1 = Dog();
Dog dog2 = Dog();

Access and modify object variables using the dot operator .:

dog1.name = 'Nicky';
dog1.breed = 'Siberian Husky';

dog2.name = 'Teemon';
dog2.breed = 'Labrador';

Access object variables:

print('${dog1.name} is a ${dog1.breed}');
// Output: Nicky is a Siberian Husky

Try it yourself

import 'student.dart';

void main() {
  // TODO: Create two Student objects


  // TODO: Set name and grade for student1 (name: 'Alice', grade: 'A')


  // TODO: Set name and grade for student2 (name: 'Bob', grade: 'B')


  print('${student1.name} has grade ${student1.grade}');
  print('${student2.name} has grade ${student2.grade}');
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming