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
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
1void main() {2 // Create an object3 Person p1 = Person();4 5 // Modify its fields6 p1.name = 'Alice';7 p1.age = 30;8 9 // Call its method10 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
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 p19Person p2 = Person(); // Bob's data inside p2HintClasses 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
Exercise 1: Create a Class
Create a Car class with fields brand and speed. Add a drive() method.
Reveal solutionHide solution
1class Car { String brand = 'Toyota'; int speed = 0; void drive() { print('Vroom'); } }Exercise 2: Use the Class
Create a Car object, set its brand to "Tesla", and call drive().
Reveal solutionHide solution
1Car c = Car(); c.brand = 'Tesla'; c.drive();