Flutter Learning Notes--Dart Object Oriented

If you need to reproduce it, please indicate the source: Flutter Learning Notes (8) --Dart Object Oriented

 

Dart, as a high-level language, supports many object-oriented features and mixin-based inheritance, which means that a class can inherit from multiple parent classes, which is equivalent to multiple inheritance in other languages.All classes have the same base class Object, which is similar to the Java language in nature, and all Java classes inherit from Object, that is, everything is an object.

//Instantiated a User Object of class user
var user = new User('Zhang San',20);
  • Instantiate member variables

Class User{
    String name;//name Member variables
    int age;//age Member variables
}

All variables in the class definition implicitly define the setter method, with additional getter methods added for non-empty variables.See the following code for instantiating member variables:

main(){
    var user = new User();
    user.name = 'Zhang San';//Equivalent to using name Of setter Method
    user.age = 25;
}
  • Constructor

1. General constructors

The constructor is a special function used to construct the current class. The name of the function must be the same as the class name. The following code adds a constructor to the User class, where two member variables of the User class are initialized with values:

Class User{
    String name;
    int age;
    User(String mName,int mAge){
        this.name = mAge;
        this.age = mAge;
    }
}

The this keyword points to an instance of the current class, and the code above can be simplified to:

Class User{
    String name;
    int age;

    User(this.name,this.age);
}

The first method initializes member variables without simplification within the method body, and the second method initializes member variables by assignment directly when instantiating the class.

2. Named constructor

Use named constructors to quickly implement constructors from another class or existing data, as follows:

Class User{
    String name;
    int age;
    //General Constructor
    User(this.name,this.age);

    //Named Constructor
    User.fromJson(Map json){
        name = json['name'];
        age = json['age'];
    }
}

//When instantiating a class, a parameterless constructor is called by default if no arguments are passed
//General Constructor
var user = new User('Zhang San',25);

//Named Constructor
var user = new User.fromJson(mMapJson);

My understanding of named constructors is that there can only be one construct with the same number of parameters in Java, and Dart is no exception. If we want to have multiple constructs with the same number of parameters, then the named construct will show its value and we canThere is no error in giving different names to the construction methods of the same number of parameters.

3. Creation of subclasses

Note 1: When a subclass inherits a parent class, it will not inherit the parent class's anonymous and parameterless constructor if an anonymous and parameterless constructor is displayed in the parent class, that is, the subclass will only inherit the parent class's anonymous and parameterless constructor.(The program implicitly generates an unnamed, parameterless constructor for the class)

Note 2: When a subclass inherits a parent class, if there is no explicit constructor in the parent class that provides an anonymous, parameterless constructor, the subclass must manually call a constructor of the parent class. In this case, the constructor of the called parent class must be placed after the subclass constructor and before the subclass constructor body, use":" Separation.

Note 3: The constructor of the parent class is called before the constructor of the child class.

Note 4: By default, subclasses can only call nameless, parameterless constructors of the parent class.

Below I will use the code to explain the above "note" (I will not at first, also understand the online search data!!!)

Notes 1 and 3: There is an anonymous, parameterless constructor in the parent class, and the subclass inherits the parent class's anonymous, parameterless constructor by default (the subclass will not call even if there are other anonymous, parameterized or named constructors), and the anonymous, parameterless constructor of the parent class will be called in the subclassThe constructor was previously called.

Class Futher {

    //Anonymous, parameterless constructor
    Futher(){
        print('I am an unnamed, parameterless constructor of the parent class');
    }
}

Class Son extends Futher {
    //Since the parent class explicitly declares an unnamed, parameterless constructor, it is not necessary to call the parent class's constructor manually.
    Son.fromJson(Map mMapJson){
        print('I am a named constructor for a subclass');
    }
}

var son = new Son.fromJson(mMapJson);
//Print results
//I am an unnamed, parameterless constructor of the parent class
//I am a named constructor for a subclass

Note 2: In the code below, the naming construction method of the subclass is written in two ways, the first is correct, the second is wrong, has detailed comments, if in doubt, please leave a message.

Class Futher {

    //Anonymous, parameterless constructor
    Futher.printSth(){
        print('I am an unnamed, parameterless constructor of the parent class');
    }
}

Class Son extends Futher {
    //Since the parent class does not explicitly declare an unnamed, parameterless constructor, you need to call the parent class's constructor manually.
    Son.fromJson(Map mMapJson) : super Futher.printSth{
        print('I am a named constructor for a subclass');
    }

    //This is an error because an unnamed, parameterless constructor is not shown in the parent class.So you need to call a constructor of the parent class manually as above
    Son.fromJson(Map mMapJson){
        print('I am a named constructor for a subclass');
    }
}

4. Initialization list of constructors

When explaining general constructors and named constructors above, the sample code initializes member variables in the class, characterized by initialization within the method body of the constructor, and another way to initialize member variables is to initialize member variables before the constructor runs.

Class User {
    String name;
    int age;

    User(mName,mAge)
        :name = mName,
        age = mAge{
            // Do Some Thing
        }
}

It is characterized by initializing member variables in front of the body of the constructor's method (before curly brackets), separated by "," among variables.

  • Read and write objects

Get() and set() methods are methods designed to read and write properties of objects, and for each instance of a class, the system implicitly contains get() and set() methods.

For example, define a rectangular class with four member variables: top, bottom, left, right. Use the get and set keywords to get and set values for right and bottom, respectively.The code is as follows:

Class Rectangle {
    num left;
    num top;
    num width;
    num height;

    Rectangle(this.left,this.top,this.width,this.height);

    num get right => left + width;//Obtain righht Value of (first line)

    set right(num value) => left = value - width;//Set up right Value of the left A change has also occurred (second line)

    num get bottom => top + height;//Obtain bottom Value of (third line)

    set bottom(num value) => top = value - height;//Set up bottom Value, while top A change has also occurred (fourth line)
}

main(){
    var rect = new Rectangle(3,4,20,15);//instantiation Rectangle,Initialize and assign values to four variables in the class

    print('left:'+rect.left.toString());//Obtain left And print left = 3
    print('right:'+rect.right.toString());//Obtain right And print the value, which is executed here Rectangle The first line of code in the class, right = left + width,right = 3+20 = 23
    rect.right = 30;//Re-give right Assignment right = 30,Executed here Rectabgke The second line of code in the class will right The value of is set to 30, and the left Change value to 30 - 20,left = 30-20 = 10
    print('right Change value to 30');
    print('left:'+rect.left.toString());//Obtain left And print the value because it gives right When reassigning, it also changes left Value of, so, at this point left = 10
    print('right:'+rect.right.toString());//rect.right = 30 take right The value changed to 30, so, right = 30


    print('top:'+rect.top.toString());
    print('bottom:'+rect.bottom.toString());
    rect.bottom = 50;
    print('bottom Change value to 50');
    print('top:'+rect.top.toString());
    print('bottom:'+rect.bottom.toString());
}

//Print results
left:3
right:23
right Change value to 30
left:10
right:30
top:4
bottom:19
bottom Change value to 50
top:35
bottom:50

The example notes above have been explained clearly, if you have any questions, please leave a message!!!

Here I'll explain what'=>'does. In Dart, you can simply understand that you're going to continue with the next steps.

  • Operator overload operation

Before explaining overloaded operators, you need to first describe a keyword operator within Dart, which is used with operators to represent an operator overloaded function and can be understood as a function name, such as operator+or operator-.Write an example to understand.

Class Vector {
    final int x;
    final int y;
    const Vector(this.x,this.y);

    //Overload plus sign + (a+b)
    Vector operator + (Vector v){
        return new Vector(x + v.x,y + v.y);
    }
}

main() {
    //Instantiate two variables
    final result1 = new Vector(10,20);
    final result2 = new Vector(30,40);

    final result = result1 + result2;

    print('result.x = '+result.x.toString()+'',+'result.y = '+result.y.toString());

    //Print results
    result.x = 40,result.y = 60
}

 

Explain the above examples. If something is wrong, leave a message to point out.

First a Vector class is created, declaring that two member variables x and y have a construction method, overloading an addition operator in the Vector class, overloading returns a Vector object, and then in the main function, instantiating two Vector variables, two operations are given to

X and y are assigned, x = 10; y = 20; x = 30; y = 40.Then let result1 and result2 add together, and you may wonder, how do the two object variables add up?Here our operator overload works, in fact, when we execute final result = result1 + result2; when we execute this line of code, the object result1 actually calls the function "operator +" and passes the object result2 to the function as a parameter, thus implementing X and X in object result1The addition of X in object result2, y in object result1, and Y in object result2, results.x = 40 and results.y = 60 for the final print.

Seeing here, do you have a certain understanding of operator overloading?If you have any questions, please leave a message to ask!!!

Note: For all operators provided by Dart, operations on basic data types and classes provided in standard libraries are generally supported, whereas for user-defined classes, if you want to perform some basic operations (such as comparing sizes, determining equality) through this operator, you need to define the user's own operations onThe implementation of this operator.

  • Inheritance Class

Inheritance is a cornerstone of object-oriented programming because it allows the creation of hierarchical classes.Inheritance is the inheritance of the parent's characteristics and behavior by a child class so that the child class object has the instance domain and method of the parent class, or that the child inherits the method from the parent class so that the child class has the same behavior as the parent class.Dart uses the extends keyword to implement inheritance, and the super keyword to specify the parent class.

Class Animal {
    void eat(){
        print('Animals eat');
    }

    void run(){
        print('Animals run');
    }
}

Class Human extends Animal {
    void say(){
        print('People will say');
    }

    void study(){
        print('People learn');
    }
}

main(){
    var animal = new Animal();
    animal.eat();
    animal.run();

    value human = new Human();
    human.eat();
    human.run();
    human.say();
    human.study();

    //Print results
    Animals eat
    //Animals run

    //Animals eat
    //Animals run
    //People will say
    //People learn
}

 

  • abstract class

Abstract classes are similar to interfaces in the Java language.There are no specific implementation methods in abstract classes, just defined interfaces, which are implemented by the caller.Abstract classes can use the abstract keyword to define classes.

  1. Abstract classes are defined by the abstract keyword.
  2. Abstract methods in Dart cannot be declared with abstract, and methods without body in Dart become Abstract methods.
  3. If a subclass inherits an abstract class, it must implement the abstract method inside.
  4. If you implement an abstract class as an interface, you must implement all the properties and methods within the abstract class.
  5. An abstract class cannot be instantiated, only subclasses that inherit it can be instantiated.
abstract class Animal{
    eat();   //Abstract method
    run();  //Abstract method  
    printInfo(){
    print('I am a common method inside an abstract class');
  }
}

class Dog extends Animal{
    @override
    eat() {
        print('Dogs are eating bones');
    }

    @override
    run() {
        // TODO: implement run
        print('The puppy is running');
    }  
}
class Cat extends Animal{
    @override
    eat() {
        // TODO: implement eat
        print('The cat is eating a mouse');
    }

    @override
    run() {
        // TODO: implement run
        print('Cat is running');
    }

}

main(){
    Dog d=new Dog();
    d.eat();
    d.printInfo();

    Cat c=new Cat();
    c.eat();
    c.printInfo();


    // Animal a=new Animal();   //Abstract classes cannot be instantiated directly
}
  • Enumeration Type

An enumeration type is a special class, usually used to represent a set of constant values of the same type, defined by enum, where each enumeration type has an index and getter that marks the element's position.The index of the first enumeration element is 0. Enumerations cannot be inherited and instances cannot be created.

//Define an enumeration class
enum Color {
    red,
    green,
    blue
}

//Print Enumeration Class green Index of
print(Color.green.index); // 1

//Gets all the values in the enumeration class, using value constant
List<Color> colorList = Color.values;

 

Because each element in the enumeration class is of the same type, the switch statement can be used to handle different values differently, as shown in the following sample code:

//Define an enumeration class
enum Color {
    red,
    green,
    blue
}

main(){
    Color mColor = Color.blue;

    switch (mColor){
        case Color.red:
        print('gules');
        break;
        
        case Color.green:
        print('green');
        break;
        
        case Color.blue:
        print('blue');
        break;

        default:
        break;
    }

    //Print results
    blue
}

 

  • Mixins

Mixins is equivalent to multiple inheritance, which means you can inherit multiple classes and use the with keyword to implement Mixins'functions. The sample code is as follows:

Class First {
    void printSth(){
        print('im first printSth');
    };
}

Class Second {
    void printSth(){
        print('im Second printSth');
    };

    void secondPrint(){
        print('test');
    }
}

Class A = Second with First;

main (){
    A a = new A();
    a.printSth();
    a.secondPrint();

    //Print results
    im first printSth
    test
}

 

This sample code mixes Class First into Class Second and gives Class A. I have a question when learning this. The same printSth method, after mixing First into Second, printSth in First is printed because the printSth method in First overrides the printSth method in Second?

  • generic paradigm

Generics are typically designed for type safety. Specifying a generic type appropriately generates better code. You can use generics to reduce code duplication, and Dart uses <T> to define generics.For example, if you want a List to contain only strings, you can declare it as list<String>.As follows:

var names = new List<String>();
names.addAll(['Zhang San','Li Si','King Five']);

Generics are used for List and Map type parameterization:

List:<type>
Map:<keyType,valueType>

var names = new List<String>['Zhang San','Li Si','King Five'];
var weeks = new Map<String,String>{
    'Monday'' : 'Monday',
    'Tuesday' : 'Tuesday',
    'Wednesday' : 'Wednesday',
    'Thursday' : 'Thursday',
    'Friday' : 'Friday',
    'Saturday' : 'Saturday',  
};

 

  • Use of Libraries

1. Reference Library

By using the import statement to reference files from one library to another, you need to be aware of the following:

1.1 The path to the library file needs to be followed by the import statement.
1.2 Use dart:xx format for library files provided by Dart language
1.3 Third party library files in package:xx format

An example of import is as follows:

import 'dart:io';
import 'package:mylib/mylib.dart';

 

2. Specify a prefix for a library

When the referenced libraries have conflicting names, you can specify different prefixes for one or more of them, which is similar to the concept of namespaces, as shown in the example code below:

import 'package:lib1/lib1.dart';
import 'package:lib2/lib2.dart' as lib2;

Element emelent1 = new Element();//Default Use lib1 Inside Element
lib2.Element emelent2 = new lib2.Element();//Use lib2 Inside Element

 

There are Element classes in lib1/lib1.dart and lib2/lib2.dart. If you refer directly, you don't know which Element class to refer to, so you specify lib2/lib2.dart as lib2 in your code so that there is no conflict with lib2.Element.3. If you only need to use a part of the library, you can optionally reference a part of the library with the following keywords:

3.1show keyword: just refer to a point
3.2 hide: all references except

The sample code is as follows:

//Import foo
import 'package:lib1/lib1.dart' show foo;

//except foo Import everything else
import 'package:lib1/lib1.dart' hide foo;

 

  • Asynchronous Support

  • metadata

  • Notes

Next Chapter: Flutter Learning Notes (9) - Common Components

Keywords: PHP Java JSON Programming

Added by martor on Thu, 18 Jul 2019 21:40:35 +0300