Classes and Objects
Prerequisites: Functions, Named and optional parameters
A class is a blueprint that describes a kind of thing: the data it holds (fields, also called properties) and what it can do (methods). An object is one actual thing built from that blueprint, also called an instance.
Real-world analogy: a class is a cookie cutter; objects are the cookies. One cutter, many cookies — each can have different icing, but they all share the same shape.
Example
class Dog {
final String name;
final String breed;
int tricks = 0;
Dog(this.name, this.breed);
String bark() => '$name says woof!';
void learnTrick() {
tricks++;
}
String describe() => '$name the $breed knows $tricks tricks';
}
void main() {
final rex = Dog('Rex', 'beagle');
final luna = Dog('Luna', 'collie');
print(rex.bark());
rex.learnTrick();
rex.learnTrick();
print(rex.describe());
print(luna.describe());
}
Expected output
Rex says woof!
Rex the beagle knows 2 tricks
Luna the collie knows 0 tricks
Line by line:
final String name;declares a field that's set once, when the object is created.int tricks = 0;is a field with a starting value that can change.Dog(this.name, this.breed);is the constructor.this.namemeans "store this argument in thenamefield" — no body needed.bark,learnTrick, anddescribeare methods. Inside them, fields are used directly by name.Dog('Rex', 'beagle')creates an instance. (Older Dart code writesnew Dog(...);newis optional and no longer used.)
Each object has its own data: teaching Rex tricks doesn't affect Luna.
Common mistakes
- Forgetting to initialize a non-nullable field:
Field 'name' should be initialized because its type 'String' doesn't allow null.Set it in the constructor, give it a default, or make it nullable. - Printing an object:
print(rex)showsInstance of 'Dog'until you overridetoString(a later lesson).
Practice
Create a BankAccount class with an owner and a balance starting at
0.0, with deposit(amount) and summary() methods. summary() should
return 'Ada has 150.0' after depositing 100 and 50.
Show solution
class BankAccount {
final String owner;
double balance = 0.0;
BankAccount(this.owner);
void deposit(double amount) {
balance += amount;
}
String summary() => '$owner has $balance';
}
void main() {
final account = BankAccount('Ada');
account.deposit(100);
account.deposit(50);
print(account.summary());
}
Ada has 150.0