【问题标题】:Question about of "Substituting types" from dart documentation关于飞镖文档中“替换类型”的问题
【发布时间】:2020-07-30 21:43:31
【问题描述】:

阅读“Dart 类型系统”中的"Substituting types" 部分我不明白为什么我从层次结构的上一层分配时会出错。

class Animal { }
class Cat extends Animal { }
class MaineCoon extends Cat { }

Animal c = Cat(); 对编译器有效,但 MaineCoon c = Cat(); 得到不正确的构造函数错误。

我不明白为什么 MaineCoon 不能转换为 Cat,但 Animal 可以转换
Cat 甚至 Animal c = MaineCoon(); 仍然有效。

【问题讨论】:

    标签: dart


    【解决方案1】:

    简答(见下面的源代码)

    void main() {
      Animal animal = Cat();
      print(animal.animalName);
      MaineCoon maineCoon = Cat();
      // Opps!!! The "Cat" does not declares "maineCoonName".
      print(maineCoon.maineCoonName);
    }
    
    class Animal {
      String animalName = 'animal';
    }
    
    class Cat extends Animal {
      String catName = 'cat';
    }
    
    class MaineCoon extends Cat {
      String maineCoonName = 'maineCoonName';
    }
    

    如果Cat 没有声明成员maineCoonName,您如何想象从实例Cat 访问maineCoonName

    附言
    即使没有声明这个成员(我的意思是maineCoonName),但这并不意味着以后不会添加类似的成员,这原则上会破坏整个程序。

    【讨论】:

      猜你喜欢
      • 2019-09-08
      • 2022-11-02
      • 2014-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多