在 Dart 编程语言中,类继承是一种重要的面向对象编程概念。
通过类继承,我们可以创建一个新的类,并从现有的类中继承属性和方法。这种方式可以提高代码的重用性和可维护性,同时也符合面向对象编程的核心原则之一: 封装、继承和多态。
在 Dart 中,一个类可以通过关键字 extends 来继承另一个类。被继承的类称为父类或超类,继承该父类的新类称为子类或派生类。
class Animal {
late String name;
late int age;
Animal(this.name, this.age);
void Say() {
print("My name is ${this.name} and I am ${this.age} years old.");
}
}
class Dog extends Animal {
late String type;
Dog(String name, int age, this.type) : super(name, age);
@override
void Say() {
print("My name is ${this.name} and I am ${this.age} years old.");
print("My type is ${this.type}.");
}
}
void main(List<String> args) {
Dog dog = Dog("wangcai", 2, "dog");
dog.Say();
}
在继承过程中,我们可以通过 supper() 函数来调用父类的构造器( 示例见上面的代码)。
我们可以通过 super 关键字来访问父类的属性或方法 :
class Animal {
late String name;
late int age;
Animal(this.name, this.age);
void Say() {
print("My name is ${this.name} and I am ${this.age} years old.");
}
}
class Dog extends Animal {
late String type;
Dog(String name, int age, this.type) : super(name, age);
@override
void Say() {
super.Say();
print("My type is ${this.type}.");
}
}
void main(List<String> args) {
Dog dog = Dog("wangcai", 2, "dog");
dog.Say();
}
在子类中定义与父类同名方法即可实现方法的复写( 如 : 上面例子中的 Say 方法 )。
建议加上 @override 元数据。
在前面的《 访问修饰 》章节我们曾经学习以 _ 开头的属性或者方法是私有的,在继承时无法继承和访问父类的私有属性或者方法。
如果非要访问私有属性可以通过公共的 setter getter 来实现。