Kế thừa (Inheritance) trong Dart
1. Giới thiệu
Kế thừa cho phép class con thừa hưởng thuộc tính và phương thức từ class cha.
2. Cú pháp kế thừa
class Animal {
String name;
Animal(this.name);
void speak() {
print('$name makes a sound');
}
}
class Dog extends Animal {
Dog(String name) : super(name);
@override
void speak() {
print('$name barks');
}
}
void main() {
var dog = Dog('Buddy');
dog.speak(); // Buddy barks
}3. Từ khóa super
class Vehicle {
String brand;
int year;
Vehicle(this.brand, this.year);
void info() {
print('$brand - $year');
}
}
class Car extends Vehicle {
int doors;
Car(String brand, int year, this.doors) : super(brand, year);
@override
void info() {
super.info(); // Gọi method cha
print('Doors: $doors');
}
}4. Override methods
class Shape {
double area() => 0;
}
class Circle extends Shape {
double radius;
Circle(this.radius);
@override
double area() => 3.14159 * radius * radius;
}
class Rectangle extends Shape {
double width, height;
Rectangle(this.width, this.height);
@override
double area() => width * height;
}5. Đa hình (Polymorphism)
void main() {
List<Shape> shapes = [
Circle(5),
Rectangle(4, 3),
];
for (var shape in shapes) {
print('Area: ${shape.area()}');
}
}6. Protected members
Dart không có protected, dùng _ cho private:
class Parent {
String _secret = 'hidden'; // Private trong library
void showSecret() {
print(_secret);
}
}
class Child extends Parent {
void reveal() {
// Có thể truy cập _secret nếu cùng file
print(_secret);
}
}7. Kế thừa constructor
class Person {
String name;
int age;
Person(this.name, this.age);
Person.guest() : name = 'Guest', age = 0;
}
class Student extends Person {
String school;
Student(String name, int age, this.school) : super(name, age);
Student.guest(this.school) : super.guest();
}8. Covariant override
class Animal {
void chase(Animal other) {
print('Chasing animal');
}
}
class Dog extends Animal {
@override
void chase(covariant Dog other) {
print('Chasing dog');
}
}📝 Tóm tắt
extendsđể kế thừasupertruy cập class cha@overrideannotation cho method override- Dart chỉ hỗ trợ single inheritance
- Dùng
covariantcho type narrowing
Last updated on