美文网首页人生几何?
9.Dart-静态成员, 继承, 操作符

9.Dart-静态成员, 继承, 操作符

作者: 你的胡霸霸 | 来源:发表于2021-09-08 00:06 被阅读0次

    /**

    * Dart中的静态成员: 其实就相当于其他语言的类方法和变量

    *    1.使用static关键字实现类级别的变量和函数

    *    2.静态方法不能访问非静态成员,非静态方法可以访问静态成员

    *

    *

    * Dart中对象操作符:

    *    ?    条件运算符 (类似swift的解包?)

    *    as  类型转换  (和swift类似)

    *    is  类型判断

    *    ..  级联操作(连缀)

    *

    *

    * Dart中的继承

    *    1.子类使用extends关键字来继承父类

    *    2.子类会继承父类里面可见的属性和方法, 但是不会继承构造函数

    *    3.子类能重写父类的方法  getter和setter

    */

    main(List<String> args) {

      var p = new Person();

      // p.show();

      Person.show();

      print(Person.name);

    // 1. 这样声明的animal,没有创建出来, 变量animal还是null, 并不能调用say函数,

    // ?在这里就是判断animal是不是null,如果不是就执行后面的say函数

      Animal animal;

      animal?.say();

    // 下面这样创建实例之后就可以使用函数了

      animal = new Animal.type("Dog");

      animal?.say();

      // 2. is判断是不是某个类型的, 如果是父类的类型也是true

      if (animal is Animal) {

        print("animal是Animal类的实例");

      } else {

        print("animal不是Animal类的实例");

      }

      var aa;

      aa = '';

      aa = new Animal.type("Cat");

      // 新版的Dart可以这么用, 之前的老版本需要用as转一下

      aa.say();

      (aa as Animal).say();

      // 3.连缀操作 ..  比较方便

      Animal monkey = new Animal.type("monkey");

      // 使用..后面直接可以给属性赋值或者调用函数, 中间不需要分号, 只是在最后一个操作后面加分号;

      monkey

        ..type = "金丝猴"

        ..age = 2

        ..say();

      Tiger t = new Tiger("老虎", "公");

      // 直接使用继承的父类的方法和属性

      t.say();

    }

    class Person {

      static String name = "张三";

      static show() {

        // 静态方法里,不能调用非静态的属性和方法

        // print(this.name);

        print(name);

      }

      int age = 20;

      des() {

        // 非静态的方法可以访问静态和非静态的方法和属性

        print("这是$name, ${this.age}");

      }

    }

    class Animal {

      String type;

      int age = 1;

      Animal.type(String type) {

        this.type = type;

      }

      Animal(type) {

        this.type = type;

      }

      // Animal(this.type);

      say() {

        print("这是${this.type}类型");

      }

    }

    class Tiger extends Animal {

      String sex;

      // 构造函数这里调用父类super的进行赋值

      Tiger(type, sex) : super(type) {

        this.sex = sex;

      }

      eat() {

        print("只吃肉!");

      }

      // 重写父类方法

      @override

      say() {

        print("${this.type}是${this.sex}的");

      }

    }

    class Dog extends Animal {

      // 给命名构造哈数传参数

      Dog.type(String type) : super.type(type);

    }

    相关文章

      网友评论

        本文标题:9.Dart-静态成员, 继承, 操作符

        本文链接:https://www.haomeiwen.com/subject/gtqqwltx.html