簡體   English   中英

Dart中inheritance的正確方式

[英]Proper way of inheritance in Dart

我有兩個父類:

class Animal {
  final String name;
  final Home home;

  Animal(this.name, this.home);
}

class Home {
  final String location;

  Home(this.location);
}

以及它們對應的子類:

class Human extends Animal {
  Human(String name, Home home) : super(name, home);

  getDetails() {
    print("$name\n");
    print("${home.getLocation()}\n");
  }
}

class House extends Home {
  House(String location) : super(location);

  String getLocation() {
    return "North side of $location";
  }
}

如您所見, Home的子 class , House包含一個方法getLocation 還有Animal的子 class , Human有一個方法getDetails需要調用getLocation方法。 但它說沒有為“Home”類型定義“getLocation”方法。

這只是我試圖理解實體模型的真實用例而編寫的一個示例,其中model實體的子對象,其中包含其他方法,例如toJson / fromJson 我無法從第一個子 class(在本例中為 Human)調用第二個子類(在本例中為 House)toJson(如本例中的 getLocation 方法)方法。

我有兩個父類:

class Animal {
  final String name;
  final Home home;

  Animal(this.name, this.home);
}

class Home {
  final String location;

  Home(this.location);
}

以及它們對應的子類:

class Human extends Animal {
  Human(String name, Home home) : super(name, home);

  getDetails() {
    print("$name\n");
    print("${home.getLocation()}\n");
  }
}

class House extends Home {
  House(String location) : super(location);

  String getLocation() {
    return "North side of $location";
  }
}

如您所見, Home的子 class , House包含一個方法getLocation 還有Animal的子 class , Human有一個方法getDetails需要調用getLocation方法。 但它說沒有為“Home”類型定義“getLocation”方法。

這只是我試圖理解實體模型的真實用例而編寫的一個示例,其中model實體的子對象,其中包含其他方法,例如toJson / fromJson 我無法從第一個子 class(在本例中為 Human)調用第二個子類(在本例中為 House)toJson(如本例中的 getLocation 方法)方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM