Dart - 继承

Dart - 继承 首页 / Dart入门教程 / Dart - 继承

Dart继承定义为派生另一个类的属性和特征的过程。它提供了从现有类创建新类的函数。它是oops(面向对象编程方法)的最基本概念。我们可以在新类中重用上一类的所有行为和特征。

  • Parent类 - 由另一类继承的类称为 supercrass 父类。它也被称为基类。
  • Child类    - 继承来自其他类的属性的类被称为子类。它也被称为派生类子类

假设我们有一支汽车队伍,我们创造了三个类,作为Duster,Maruti和Jaguar。方法modelName(),milage(),和man_year()对于所有三个类都将相同。通过使用继承,我们不需要在三个类中的每一个中编写这些函数。

Dart Inheritance

正如您在上图中看到的那样,如果我们创建Class Car并在每个类中写下常用函数。然后,它将增加程序中的重复和数据冗余。继承用于避免这种情况。

让我们看看以下图像。

Dart Inheritance

语法 -

class child_class extends parent_class {
    //body of child class
}

子类继承函数和变量,或使用extends关键字继承父类的属性。它无法继承父类构造函数;我们稍后会讨论这个概念。

链接:https://www.learnfk.comhttps://www.learnfk.com/dart-programming/dart-inheritance.html

来源:LearnFk无涯教程网

继承类型

继承可能主要下面几种类型。

  • 单个继承
  • 多级继承
  • 分层继承

单个继承

在单个继承中,一个类是由单个类或子类继承的一个父类继承。

Dart Inheritance

让我们了解以下示例。

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

多级继承

在多重继承中,子类被另一个子类继承或创建继承链。让我们了解以下示例。

Dart Inheritance

示例 -

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

分层继承

在分层固有中,两个或多个类继承了单个类。

Dart Inheritance

示例 -

// 父类
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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

人工智能基础课 -〔王天一〕

设计模式之美 -〔王争〕

分布式系统案例课 -〔杨波〕

Vim 实用技巧必知必会 -〔吴咏炜〕

重学线性代数 -〔朱维刚〕

Redis核心技术与实战 -〔蒋德钧〕

商业思维案例笔记 -〔曹雄峰〕

现代React Web开发实战 -〔宋一玮〕

结构思考力 · 透过结构看思考 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)