Dart继承定义为派生另一个类的属性和特征的过程。它提供了从现有类创建新类的函数。它是oops(面向对象编程方法)的最基本概念。我们可以在新类中重用上一类的所有行为和特征。
假设我们有一支汽车队伍,我们创造了三个类,作为Duster,Maruti和Jaguar。方法modelName(),milage(),和man_year()对于所有三个类都将相同。通过使用继承,我们不需要在三个类中的每一个中编写这些函数。
正如您在上图中看到的那样,如果我们创建Class Car并在每个类中写下常用函数。然后,它将增加程序中的重复和数据冗余。继承用于避免这种情况。
让我们看看以下图像。
语法 -
class child_class extends parent_class { //body of child class }
子类继承函数和变量,或使用extends关键字继承父类的属性。它无法继承父类构造函数;我们稍后会讨论这个概念。
链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-inheritance.html
来源:LearnFk无涯教程网
继承可能主要下面几种类型。
在单个继承中,一个类是由单个类或子类继承的一个父类继承。
让我们了解以下示例。
class Bird{ void fly() { print("The bird can fly"); } } //继承超类 class Parrot extends Bird{ //子类函数 void speak(){ print("The parrot can speak"); } } void main() { //创建子类的对象 Parrot p=new Parrot(); p.speak(); p.fly(); }
输出
The parrot can speak The bird can fly
在多重继承中,子类被另一个子类继承或创建继承链。让我们了解以下示例。
示例 -
class Bird{ void fly() { print("The bird can fly"); } } //继承超类 class Parrot extends Bird{ void speak(){ print("The parrot can speak"); } } // 继承Parror基类 class Eagle extends Parrot { void vision(){ print("The eagle has a sharp vision"); } } void main() { //创建子类的对象 Eagle e=new Eagle(); e.speak(); e.fly(); e.vision(); }
输出
The parrot can speak The bird can fly The eagle has a sharp vision
在分层固有中,两个或多个类继承了单个类。
示例 -
// 父类 class Person { void dispName(String name) { print(name); } void dispAge(int age) { print(age); } } class Peter extends Person { void dispBranch(String nationality) { print(nationality); } } //从另一个派生类创建的派生类。 class James extends Person { void result(String result){ print(result); } } void main() { //创建 James 类的对象 James j = new James(); j.dispName("James"); j.dispAge(24); j.result("Passed"); //创建 Peter 类的对象 Peter p = new Peter(); p.dispName("Peter"); p.dispAge(21); p.dispBranch("Computer Science"); }
输出
James 24 Passed Peter 21 Computer Science
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)