Flutter dart inheritance

Inheritance is one of the three major object-oriented features, and inheritance in dart is almost consistent with java

  1. single inheritance
  2. Can inherit the public properties and methods of the parent class
  3. You can override the method of the parent class
  4. You can override the computed property of the parent class
  5. You cannot override inheritance to access the private properties of the parent class
  6. The parameterized constructor of the parent class must be called explicitly
  7. The initializer list must be called before the constructor
void main(){
 Person student = Student("张三");
 if(student is Student){
   student.number = "1001";
   student.info();
 }

}


class Person{
  String name;
  int age;
  Person(this.name,this.age);
  Person.withName(this.name);

}

class Student extends Person { 
  String number ; 
  Student ( String name )  : super.withName ( name ) ; 
  void info ( ) { 
    print ( "Student info $name " ) ; 
  } 
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25

The initializer list must call the case before the constructor

void main() {
  Person student = Student("张三","男");
  if (student is Student) {
    student.number = "1001";
    student.info();
  }
}

class Person {
  String name;
  int age;

  Person(this.name, this.age);

  Person.withName(this.name);
}

class Student extends Person {
  String number;
  final String gender;

  Student(String name, String gender)
      : gender = gender,
        super.withName(name);

  void  info ( )  { 
    print ( "Student info $name / $gender" ) ; 
  } 
}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

Related: Flutter dart inheritance