What are Classes and Objects?
A class is a blueprint that defines the properties (fields) and behaviors (methods) of a type. An object is a specific instance of a class — it holds actual data following the blueprint.
Defining a Class
class Person {
// Fields (properties)
String name;
int age;
String email;
// Constructor
Person(this.name, this.age, this.email);
// Methods (behaviors)
void introduce() {
print('Hi, I am $name, $age years old.');
}
bool isAdult() => age >= 18;
@override
String toString() => 'Person($name, age=$age)';
}
Creating Objects
void main() {
// Create objects (instances of Person)
Person alice = Person('Alice', 28, 'alice@email.com');
Person bob = Person('Bob', 17, 'bob@email.com');
// Or use var / final
var carol = Person('Carol', 32, 'carol@email.com');
}
Accessing Members
void main() {
var p = Person('Alice', 28, 'alice@email.com');
// Access fields
print(p.name); // Alice
print(p.age); // 28
// Call methods
p.introduce(); // Hi, I am Alice, 28 years old.
print(p.isAdult()); // true
// Modify fields
p.age = 29;
print(p); // Person(Alice, age=29)
}
Full Example
class BankAccount {
String owner;
double balance;
BankAccount(this.owner, this.balance);
void deposit(double amount) {
balance += amount;
print('Deposited \$$${amount.toStringAsFixed(2)}. Balance: \$$${balance.toStringAsFixed(2)}');
}
void withdraw(double amount) {
if (amount > balance) {
print('Insufficient funds!');
return;
}
balance -= amount;
print('Withdrew \$$${amount.toStringAsFixed(2)}. Balance: \$$${balance.toStringAsFixed(2)}');
}
}
void main() {
var account = BankAccount('Alice', 1000.0);
account.deposit(500.0);
account.withdraw(200.0);
account.withdraw(2000.0);
}
Output:Deposited $500.00. Balance: $1500.00
Withdrew $200.00. Balance: $1300.00
Insufficient funds!
💪 Exercise
- Create a
Car class with fields: make, model, year, and a method getInfo().
- Create a
Rectangle class with width and height. Add methods for area and perimeter.
- Create a
Student class and a list of 3 students, then print them all.
🧠 Quiz
1. What is the difference between a class and an object?
- A) They are the same thing
- B) A class is a blueprint; an object is a specific instance ✅
- C) An object is a blueprint; a class is an instance
- D) Classes have methods; objects do not
Summary
A class defines the structure (fields) and behavior (methods) of a type. Objects are instances of a class. Create objects with ClassName(args). Access fields and methods with the dot operator. Each object has its own copy of the field values.