class

Classes are one of the most important aspects of any object-oriented language. To help us learn and understand the design of some of the functionality we need to take a good look at Dart’s classes: The classes in Dart are single-inherited and have no method overloading

Create a class

  • Methods/Properties Create a class, much like Java, that defines properties, constructors, and methods. When instantiated, new is not written, but is passed as the constructor parameter, and a Rect instance is created.

    class Rect{
      int width = 0;
      int height = 0;
      Rect(int width,int height){
        this.width = width;
        this.height = height;
      }
      int area()=>width * height;
    }
    
    var rect = Rect(10.12);
    print(rect.area());
    Copy the code
  • Static methods and properties static methods and properties are simple, add static.

      class Rect{
        int width = 0;
        int height = 0;
        static demo = 10;
        Rect(int width,int height){
          this.width = width;
          this.height = height;
        }
        int area()=>width * height;
        static Area(int width, int height) => width * height;
      }
    Copy the code
  • Unlike Java, our default properties are accessible to the outside world, so we don’t need to write tedious GET and set methods. However, if you want to listen for property changes, get and set are a good solution.

    class Rect{
      int width = 0;
      int height = 0;
      
      set setWidth(int width) {
        this.width = width;
      }
    
      int get getWidh {
        return this.width; }}Copy the code

The constructor

  • Initialize a list Everyone knows that the constructor parameters passed is generally to specific attributes, therefore, if you no other things to do in the constructor, the Dart is provides a simplified way: the initialization list In addition to simplify the constructor method and it can also be in the constructor to the attribute of a final assignment. Final values can only be assigned once. So the traditional way of writing it is an error: when the constructor body is executed, the properties are already created.

    // The traditional way of writing
    class Rect{
      final int width; // Final can only be assigned once. So the traditional way of writing it gives you an error.
      int height = 0;
      Rect(int width,int height){
        this.width = width;
        this.height = height; }}// Simplify
    class Rect{
      int width = 0;
      int height = 0;
      Rect(this.width,this.height);
    }
    
    // ru1
    Copy the code
  • Name the constructor because Dart is not method overloaded. But different constructors to create classes are necessary for actual development. Hence this: Named constructors In my opinion, named constructors + named parameters of functions are simply normal function writing for Object-c. It’s a little tricky though. But when you read the code, it’s very clear, it makes sense. We can also simplify our named constructor by redirecting the constructor

    class Rect{
      int width = 0;
      int height = 0;
      Rect(this.width,this.height);
      // Name the constructor
      //Rect.fromJson(Map json){
      // this.width = json["width"];
      // this.width = json["height"];
      / /}
      // The redirection constructor simplifies assignment
      Rect.fromJson(Map json) : this(json["width"], json["height"]);
    }
    
    var rect = Rect.fromJson({"width": 1."height": 2});
    Copy the code
  • The factory method to construct If we want to create a singleton, we hope that the class at any time can return objects created for the first time, so we need to control object constructor returns, and in the constructor of the introduction, we are unable to control the object returned, so the factory construction method was born.

    class Singleton {
      static Singleton instance;
      Singleton() {}
      factory Singleton.shareInstance() {
        if(instance ! =null) {
          instance = Singleton();
        }
        returninstance; }}Copy the code

Inheritance (extends)

Extends allows you to put all the properties and methods of a class into a new class. In addition to adding your own unique methods to the new class, you can also access the parent class’s methods via super and override the parent class’s methods via @Override.

class Animal {
  String name;
  Animal(this.name);
  void say() {
    print(this.name); }}class Cat extends Animal {
  Cat(String name) : super(name);

  @override
  void say() {
    print("my name is " + this.name); }}Copy the code

An abstract class

Abstract is defined by abstract class, and abstract class, there are only names, but no content method, this is called abstract method.

  • The abstract class cannot be instantiated
  • Subclasses that extend an abstract class must implement the abstract methods in the abstract class.
  • Methods already implemented by the abstract class cannot pass@overrideRevised.
abstract class Animal {
  String name;
  Animal(this.name);
  void eat();
  void say() {
    print(this.name); }}class Cat extends Animal {
  Cat(String name) : super(name);

  @override
  void eat() {
    print(this.name + " eat fish"); }}Copy the code

Interface (implements)

In DART, all classes are interfaces. So you can directly implement all classes, unlike extends. Once implements the specified class, you must implement all of its methods. You can’t call super. Because super belongs to the superclass. Since most of the time we use interfaces just to agree on a specification, let’s call the specified interface method. So DART typically uses abstract classes as interfaces. This way, you don’t want to implement the same method again and again.

class Animal {
  String name;
  Animal(this.name);
  void say() {
    print(this.name); }}class Action {
  void eat() {
    print("eat"); }}class Cat extends Animal implements Action {
  Cat(String name) : super(name);

  @override
  void say() {
    print("my name is " + this.name);
  }

  @override
  void eat() {
    print(this.name + " eat"); }}Copy the code

Mix (a mixin)

Implements just use the body of a class. Each method needs to be implemented again on a new class. It cannot be used directly like extends, but extends is only a single inheritance. So this new feature of blending was born in DART.

class Animal {
  String name;
  Animal(this.name);
  void say() {
    print(this.name); }}class Action {
  String action;
  void doSomeThing() {
    print(this.action); }}class Cat extends Animal with Action {
  Cat(String name) : super(name);

  @override
  void say() {
    print("my name is " + this.name);
  }
}

main(List<String> args) {
  var cat = Cat('cat');

  cat.say();
  cat.action = "eat";
  cat.doSomeThing();
}
Copy the code

Inheritance, blending, interface differences

One of the biggest puzzles when you first start using Dart is the difference between with, extends and implements.

  • On the ideological level:
    • extendsIs the common practice of object-oriented, mainly in order to extract the characteristics of similar things, so as to achieve the reuse of code,
    • withThe idea is mainly combination, not only similar things have these characteristics, we can extract the same logic of different kinds of things out and use.
    • implementsThe idea is conventions, and each interface is a convention and a rule, according to which we implement our methods.
  • From the use level
    • extendsJust like normal inheritance, you give all the methods and attributes to the new class, and the new class can access the parent class, and it can choose whether or not to overwrite the parent class. After inheritance, the two are still related
    • withMuch like inheritance, except that it always takes precedence over inheritance: methods and attributes of the same name are subject to inheritance
    • implementsYou can treat any class that implements as abstract because you have to implement all its methods, right