Summary - Class basics
- Dart course
- Beginner
- Lesson 82/116
- 5 min
Combine class, constructor and methods to write a User class.
Summary - Class basics
This group covered class basics. class declares a class; the constructor prepares the instance; instance variables hold data; methods define behavior; this disambiguates field and parameter.
The short constructor User(this.name) equals the long User(String name) { this.name = name; }. The class name starts with a capital; an instance is created with User().
In the final task you will blend everything into a User class: both name and age fields, a constructor, and a describe method. This will be a small but real class.
Practice User class with constructor
Define a User class with a String name field and a User(this.name) constructor. Inside main create a User('Ayşe') instance and print it with print(u.name).
Starter code
void main() {
// define the User class
// create an instance and print
}Sample solution
class User {
String name;
User(this.name);
}
void main() {
var u = User('Ayşe');
print(u.name);
}Expected output
Ayşe
Practice Full User class
Define a User class with String name and int age fields, a User(this.name, this.age) constructor, and a void describe() method. The method body should do print('$name, $age'). Inside main create a User('Ayşe', 28) instance and call u.describe().
Starter code
void main() {
// define the User class
// create an instance and call describe
}Sample solution
class User {
String name;
int age;
User(this.name, this.age);
void describe() {
print('$name, $age');
}
}
void main() {
var u = User('Ayşe', 28);
u.describe();
}Expected output
Ayşe, 28
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the concepts
| Term | Meaning |
|---|---|
class |
Class declaration |
constructor |
Instance preparation |
instance variable |
Data |
this |
This instance |
2 When is the constructor called?
- When a method is called
- When the class is declared
- When an instance is created Correct answer
- Never
Explanation: the constructor is called when an instance is created.
3 Method call
void main() {
var u = User('Ayşe');
u.____();
}
void main() {
var u = User('Ayşe');
u.describe();
}
Explanation: describe is called on the instance.