当子类尝试覆盖父类的方法时, dart会发生方法覆盖。当子类扩展父类时,它可以完全访问父类的方法,从而覆盖父类的方法。它是通过重新定义父类中存在的相同方法来实现的。
当您必须为不同的子类执行不同的功能时,此方法很有用,因此我们可以通过覆盖它来简单地重新定义内容。
要点:
- 一个方法只能在子类中被覆盖,而不能在父类本身中被覆盖。
- 子类和父类中定义的方法都应该是精确的副本,从名称到参数列表,除了方法内部存在的内容,即它可以和不能相同。
- 在父类中声明为 final 或 static 的方法不能被子类覆盖。
- 父类的构造函数不能被继承,所以它们不能被子类覆盖。
示例 1:方法覆盖的简单案例。
Dart
// Dart Program to illustrate the
// method overriding concept
class SuperGeek {
// Creating a method
void show(){
print("This is class SuperGeek.");
}
}
class SubGeek extends SuperGeek {
// Overriding show method
void show(){
print("This is class SubGeek child of SuperGeek.");
}
}
void main() {
// Creating objects
//of both the classes
SuperGeek geek1 = new SuperGeek();
SubGeek geek2 = new SubGeek();
// Calling same function
// from both the classes
// object to show method overriding
geek1.show();
geek2.show();
}
Dart
// Dart Program to illustrate the
// method overriding concept
class SuperGeek {
// Creating a method
void show(){
print("This is class SuperGeek.");
}
}
class SubGeek1 extends SuperGeek {
// Overriding show method
void show(){
print("This is class SubGeek1 child of SuperGeek.");
}
}
class SubGeek2 extends SuperGeek {
// Overriding show method
void show(){
print("This is class SubGeek2 child of SuperGeek.");
}
}
void main() {
// Creating objects of both the classes
SuperGeek geek1 = new SuperGeek();
SubGeek1 geek2 = new SubGeek1();
SubGeek2 geek3 = new SubGeek2();
// Calling same function
// from both the classes
// object to show method
// overriding
geek1.show();
geek2.show();
geek3.show();
}
输出:
This is class SuperGeek.
This is class SubGeek child of SuperGeek.
示例 2:当有多个子类时。
Dart
// Dart Program to illustrate the
// method overriding concept
class SuperGeek {
// Creating a method
void show(){
print("This is class SuperGeek.");
}
}
class SubGeek1 extends SuperGeek {
// Overriding show method
void show(){
print("This is class SubGeek1 child of SuperGeek.");
}
}
class SubGeek2 extends SuperGeek {
// Overriding show method
void show(){
print("This is class SubGeek2 child of SuperGeek.");
}
}
void main() {
// Creating objects of both the classes
SuperGeek geek1 = new SuperGeek();
SubGeek1 geek2 = new SubGeek1();
SubGeek2 geek3 = new SubGeek2();
// Calling same function
// from both the classes
// object to show method
// overriding
geek1.show();
geek2.show();
geek3.show();
}
输出:
This is class SuperGeek.
This is class SubGeek1 child of SuperGeek.
This is class SubGeek2 child of SuperGeek.