Thuta Learning
IntermediateProgrammingbeginner

Inheritance

Relax. We'll talk through this in plain words — no textbook voice.

Inheritance is an OOP concept that lets one class take on the fields and methods of another class. You write common behavior once in a parent class, and child classes can reuse it.

dart
class User {
  final String name;

  User(this.name);

  void login() {
    print('$name logged in.');
  }
}

class AdminUser extends User {
  AdminUser(String name) : super(name);

  void deletePost() {
    print('$name deleted a post.');
  }
}

void main() {
  final admin = AdminUser('Admin Sai');
  admin.login();
  admin.deletePost();
}

AdminUser inherits from User via extends, so it can use the login() method. super(name) calls the parent constructor and passes along the name value.

You should see
Admin Sai logged in. Admin Sai deleted a post.

Easy traps

  • Overuse inheritance and your class relationships turn into a tangled mess. Check whether it's really an 'is-a' relationship before reaching for it. AdminUser is a type of User, so it's a good fit here.
Inheritance | Thuta Learning