Dart - 接口

Dart - 接口 首页 / Dart入门教程 / Dart - 接口

接口定义任何实体必须遵守的语法。 Dart没有任何单独的语法来定义接口。接口定义与类相同,其中对象可以访问任何方法集。 Class声明可以本身进行接口。

需要implement关键词,然后是类名才能使用该接口。实现类必须提供已实现接口的所有功能的完整定义。

class ClassName implements InterfaceName

在下面的示例中,我们声明一个Employee类。隐式地,Engineer类实现Employee类的接口声明。让我们通过以下代码片段来理解上面的示例。

class Employee
{
   void display() {
         print("I am working as an engineer");
   }
}
// 通过 interface 另一个类来定义接口
class Engineer implements Employee 
{
          void display() {
                 print("I am an engineer in this company");                 
          }
}
void main() 
{
  Engineer eng = new Engineer();
  eng.display();
}

输出:

I am working as engineer

实现多重继承

我们之前讨论过,Dart不支持多重继承,但我们可以应用多个接口。我们可以说,使用多个接口,我们可以在DART中实现多重继承。说法如下。

class ClassName implements interface1, interface2,…interface n

让我们了解以下示例。

class Student
{
   String name;
   int age;
   
   void displayName() {
         print("I am ${name}");
   }
   void displayAge() {
            print("My age is ${age}");
   }
}

class Faculty
{
   String dep_name;
   int salary;
   
   void displayDepartment() {
         print("I am a professor of ${dep_name}");
   }
   void displaySalary() {
            print("My salary is ${salary}");
   }
}
// 通过实现另一个类来定义接口
class College implements Student,Faculty
{  
  //覆盖学生类成员
   String name;
   int age;
   
   void displayName() {
         print("I am ${name}");
   }
   void displayAge() {
            print("My age is ${age}");
   }

//覆盖 Faculty 类的每个数据成员
   String dep_name;
   int salary;
   
   void displayDepartment() {
         print("I am a proffesor of ${dep_name}");
   }
   void displaySalary() {
            print("My salary is ${salary}");

   }
}
void main() 
{
  College cg = new College();
  cg.name = "Learnfk";
  cg.age = 25;
  cg.dep_name = "Data Structure";
  cg.salary = 50000;

  cg.displayName();
  cg.displayAge();
  cg.displayDepartment();
  cg.displaySalary();
}

输出:

I am Learnfk
My age is 25
I am a professor of Data Structure
My salary is 50000

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

    技术教程推荐

    Service Mesh实践指南 -〔周晶〕

    硅谷产品实战36讲 -〔曲晓音〕

    Android开发高手课 -〔张绍文〕

    Vue开发实战 -〔唐金州〕

    趣谈Linux操作系统 -〔刘超〕

    如何讲好一堂课 -〔薛雨〕

    B端产品经理入门课 -〔董小圣〕

    AI大模型系统实战 -〔Tyler〕

    互联网人的数字化企业生存指南 -〔沈欣〕

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