extends 、 implements 、 with的用法與區(qū)別

Flutter Dart語法(1):extends 、 implements 、 with的用法與區(qū)別

在Flutter中,有如下三種關(guān)系:

  1. 繼承(關(guān)鍵字 extends)
  2. 混入 mixins (關(guān)鍵字 with)
  3. 接口實(shí)現(xiàn)(關(guān)鍵字 implements)

這三種關(guān)系可以同時(shí)存在,但是有前后順序:

extends -> mixins -> implements

extens在前,mixins在中間,implements最后,接下來看具體的例子。

1. 繼承(extends)

Flutter中的繼承和Java中的繼承是一樣的:

  1. Flutter中的繼承是單繼承
  2. 構(gòu)造函數(shù)不能繼承
  3. 子類重寫超類的方法,要用@override
  4. 子類調(diào)用超類的方法,要用super

Flutter中的繼承也有和Java不一樣的地方:

  1. Flutter中的子類可以訪問父類中的所有變量和方法,因?yàn)镕lutter中沒有公有、私有的區(qū)別

講完特性,看下面的代碼加深理解:

class Television {
  void turnOn() {
    _illuminateDisplay();
  }

  void _illuminateDisplay(){
  }
}

class SmartTelevision extends Television {
  void turnOn() {
    super.turnOn();
    _bootNetworkInterface();
  }

  void _bootNetworkInterface(){
  }
}
復(fù)制代碼

2.混合 mixins (with)

在Flutter 中:

  1. 混合的對象是類
  2. 可以混合多個(gè)

mixins 具體的特性,可以查看我之前寫得文章:Flutter mixins 探究

看具體代碼:

class Television {
  void turnOn() {
    _illuminateDisplay();
  }

  void _illuminateDisplay(){
  }
}

class Update{
  void updateApp(){

  }
}

class Charge{

  void chargeVip(){

  }
}

class SmartTelevision extends Television with Update,Charge  {

  void turnOn() {
    super.turnOn();
    _bootNetworkInterface();
    updateApp();
    chargeVip();
  }

  void _bootNetworkInterface(){
  }

}
復(fù)制代碼

3.接口實(shí)現(xiàn)(implements)

Flutter是沒有interface的,但是Flutter中的每個(gè)類都是一個(gè)隱式的接口,這個(gè)接口包含類里的所有成員變量,以及定義的方法。

如果有一個(gè)類 A,你想讓類B擁有A的API,但又不想擁有A里的實(shí)現(xiàn),那么你就應(yīng)該把A當(dāng)做接口,類B implements 類A.

所以在Flutter中:

  1. class 就是 interface
  2. 當(dāng)class被當(dāng)做interface用時(shí),class中的方法就是接口的方法,需要在子類里重新實(shí)現(xiàn),在子類實(shí)現(xiàn)的時(shí)候要加@override
  3. 當(dāng)class被當(dāng)做interface用時(shí),class中的成員變量也需要在子類里重新實(shí)現(xiàn)。在成員變量前加@override
  4. 實(shí)現(xiàn)接口可以有多個(gè)

看如下的代碼:

class Television {
  void turnOn() {
    _illuminateDisplay();
  }

  void _illuminateDisplay(){
  }
}

class Carton {
  String cartonName = "carton";

  void playCarton(){

  }
}

class Movie{
  void playMovie(){

  }
}

class Update{
  void updateApp(){

  }
}

class Charge{

  void chargeVip(){

  }
}

class SmartTelevision extends Television with Update,Charge implements Carton,Movie {
  @override
  String cartonName="SmartTelevision carton";

  void turnOn() {
    super.turnOn();
    _bootNetworkInterface();
    updateApp();
    chargeVip();
  }

  void _bootNetworkInterface(){
  }

  @override
  void playCarton() {
    // TODO: implement playCarton
  }

  @override
  void playMovie() {
    // TODO: implement playMovie
  }

}

轉(zhuǎn)載來源

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。