[Dart] Understand Classes and Inheritance in Dart
We will look at how we can create classes and explore some various features. Dart adopts a single-inheritance model, meaning that you can only extend a single class. We will therefore extend our class example by creating an Employee subclass of a parent Person class.
A normal class:
class Person { String name; int age; Person(name, age) { this.name = name; this.age = age; } }
We can also use short hand syntax:
class Person { String name; int age; Person(this.name, this.age); }
We can have optional arguements, override operator, and getter, setter:
class Person { // private name String _name; int age; String occupaction; // optional {this.occupation} Person(this._name, this.age, {this.occupaction}); // optional [this.occupaction] Person.fromJson(Map json, [this.occupaction]) { _name = json['name']; age = json['age']; } // override == operator, define a custom one bool operator ==(dynamic b) => _name == b.name && age == b.age && occupaction == b.occupation; String get name => _name; void set name(String updateName) => _name = updateName; speak() { print("My name is &_name. I'm $age years old."); } }
Use:
void main() { Person johnny = Person('Johnny', 42, occupaction: 'WD') ..speak(); // My name is &_name. I'm 42 years old. Person jane = Person.fromJson({'name': 'Johnny', 'age': 42, 'occupation': 'WD'}); print(jane == johnny); // true }
Here '..speak()' the same as:
Person johnny = Person('Johnny', 42, occupation: 'Pilot') johnny.speak()
---
void main() { Person johnny = Person('Johnny', 42, occupation: 'Pilot') ..speak() ..name = 'Big Johnny' ..speak(); print(johnny.name); print(johnny.occupation); Person jane = Person.fromJson({'name': 'Jane', 'age': 39}, 'Web Developer'); jane.speak(); print(jane.occupation); print(johnny == jane); Person jane2 = Person('Jane', 39, occupation: 'Web Developer'); print(jane == jane2); var bob = Employee('Bob', 23, DateTime.now()); bob.speak(); } class Employee extends Person { Employee(String name, int age, this.joinDate): super(name, age); final DateTime joinDate; @override speak() { print('My name is $name. I joined on $joinDate'); } } class Person { Person(this._name, this.age, {this.occupation}); Person.fromJson(Map json, [this.occupation]) { _name = json['name']; age = json['age']; } String _name; int age; String occupation; String get name => _name; void set name(String updatedName) => _name = updatedName; // If overriding the == operator, you should also override the Object's `hashCode` getter // Learn more at https://www.dartlang.org/guides/libraries/library-tour#implementing-map-keys bool operator ==(dynamic b) => _name == b.name && age == b.age && occupation == b.occupation; speak() { print("My name is $_name. I'm $age years old."); } // void _hiddenMethod() { // print('This method is hidden'); // } }