Classes and Objects
Defining classes with fields and methods, creating instances, and the this keyword.
읽는 데 2분
Dart is a genuinely object-oriented language — every value, including numbers and functions, is an instance of some class. Defining your own classes is how you model the things your program actually deals with, instead of passing loose collections of variables around.
Defining a class
class Book {
String title;
String author;
int pages;
Book(this.title, this.author, this.pages);
void describe() {
print('$title by $author ($pages pages)');
}
}
void main() {
final book = Book('Dart in Depth', 'A. Developer', 240);
book.describe(); // Dart in Depth by A. Developer (240 pages)
}title, author, and pages are fields — the data each Book carries. describe() is a method — behavior that operates on that data. Book(this.title, this.author, this.pages) is a constructor; we'll go deeper on constructors in the next lesson, but the shorthand this.title is worth noting now: it assigns the constructor's title parameter straight to the field of the same name, without a separate assignment line.
Creating instances
Each call to Book(...) creates a distinct instance — its own independent copy of the fields:
final book1 = Book('Dart Basics', 'Author A', 150);
final book2 = Book('Advanced Dart', 'Author B', 300);
print(book1.title); // Dart Basics
print(book2.title); // Advanced Dart
book1.pages = 160; // book2 is completely unaffectedNote that book1 and book2 are declared final — that fixes which Book object the variable refers to, not the object's fields. book1.pages = 160 is legal because you're mutating the object itself, not reassigning the variable; book1 = book2 would not be, because that would be a reassignment.
Getters and setters, briefly
A method that reads like a field is a getter; you'll see the full pattern (including setters, for controlled writes) in a dedicated lesson shortly, but it's worth seeing the shape now since it's so common:
class Rectangle {
double width;
double height;
Rectangle(this.width, this.height);
double get area => width * height;
}
final rect = Rectangle(4, 5);
print(rect.area); // 20.0 — read like a field, computed like a methodMethods that use this
Inside a method, this refers to the current instance — most useful when a parameter name would otherwise shadow a field of the same name:
class Counter {
int count = 0;
void incrementBy(int count) {
this.count += count; // this.count is the field; count is the parameter
}
}Without this.count, count += count would refer only to the parameter, leaving the field untouched — this disambiguates exactly which count you mean.
Classes are the foundation for almost everything past this point in the course: constructors, inheritance, mixins, and generics are all refinements of the same basic idea — bundling data and the behavior that belongs with it into one reusable definition.