class
- Dart course
- Beginner
- Lesson 77/116
- 5 min
Learn to define classes with class.
The class keyword
In Dart a class is defined with the class keyword. Example: class User { }. Inside the curly braces you write properties and methods.
A class is a blueprint for objects. It holds data (instance variables) and behavior (methods). You can create as many instances of a class as you need.
To create an instance, call the class name like a function: var u = User();. This runs the class constructor and returns a new object. Class names start with an uppercase letter in Dart; this is a convention.
Class members
A class has two kinds of members: instance variables hold data; methods define behavior. Example: class User { String name; void describe() { ... } }.
Reach instance variables with a dot: u.name. Call methods the same way: u.describe(). The dot means 'member of the instance'.
This is how access works from outside the class. Inside the class's own methods you can refer to members directly: name or this.name. this is the topic of a later lesson.
Practice Define a User class
Define a User class whose String name property starts as 'Ayşe'. Inside main create an instance with User() and print the name with print(u.name).
Starter code
void main() {
// define the User class (outside main)
// create an instance and print
}Sample solution
class User {
String name = 'Ayşe';
}
void main() {
var u = User();
print(u.name);
}Expected output
Ayşe
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 The class skeleton
class User {
// özellikler buraya
}
void main() {
var u = ____();
}
class User {
// özellikler buraya
}
void main() {
var u = User();
}
Explanation: the class name is called with a capital letter and parentheses.
2 Match the class parts
| Term | Meaning |
|---|---|
class |
Class declaration |
User |
Class name |
{} |
Class body |
u.name |
Property access |
3 How does a class name start?
- Lowercase
- Uppercase Correct answer
- Underscore
- Digit
Explanation: Dart class names start with an uppercase letter.