How to extend class in Dart?

by maryam_feest , in category: Other , 2 years ago

How to extend class in Dart?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by edison.lang , 2 years ago

@maryam_feest you can use the keyword extends to extend any class in Dart, below is an example SuperUser class which extends User class in Dart:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class User {
  User(this.username, this.password);
  
  String username;
  String password;

  void sayHello() {
    print('Hello ' + this.username);
  }
}

class SuperUser extends User {
  SuperUser(String username, String password) : super(username, password);
  
   void sayHello() {
    print('Hello SuperUser');
  }
}

void main() {
    var user = new User("test", "test2");
  
    // Output: Hello test
    user.sayHello();
  
    var superUser = new SuperUser("test", "test2");
  
    // Output: Hello SuperUser
    superUser.sayHello();
}
by taya_block , 10 months ago

@maryam_feest 

To extend a class in Dart, use the 'extends' keyword followed by the name of the class you want to extend. Here's an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Animal {
  void eat() {
    print('Animal is eating.');
  }
}

class Dog extends Animal {
  void bark() {
    print('Dog is barking.');
  }
}

void main() {
  Dog dog = Dog();
  dog.eat(); // Output: Animal is eating.
  dog.bark(); // Output: Dog is barking.
}


In the example above, we've created a class 'Animal' with a method 'eat'. Then we created a subclass 'Dog' that extends the 'Animal' class. The 'Dog' class adds a new method 'bark'. Finally, in the 'main' function, we created a new 'Dog' object and called the 'eat' and 'bark' methods. Since 'Dog' extends 'Animal', it also inherits the 'eat' method.