Extending a class

Use extends to create a subclass, and super to refer to thesuperclass:

  1. class Television {
  2. void turnOn() {
  3. _illuminateDisplay();
  4. _activateIrSensor();
  5. }
  6. // ···
  7. }
  8.  
  9. class SmartTelevision extends Television {
  10. void turnOn() {
  11. super.turnOn();
  12. _bootNetworkInterface();
  13. _initializeMemory();
  14. _upgradeApps();
  15. }
  16. // ···
  17. }

Overriding members

Subclasses can override instance methods, getters, and setters.You can use the @override annotation to indicate that you areintentionally overriding a member:

  1. class SmartTelevision extends Television {
  2. @override
  3. void turnOn() {...}
  4. // ···
  5. }

To narrow the type of a method parameter or instance variable in code that istype safe,you can use the covariant keyword.

Overridable operators

You can override the operators shown in the following table.For example, if you define aVector class, you might define a + method to add two vectors.

<+|[]
>/^[]=
<=~/&~
>=*<<==
%>>

Note: You may have noticed that != is not an overridable operator. The expression e1 != e2 is just syntactic sugar for !(e1 == e2).

Here’s an example of a class that overrides the + and - operators:

  1. class Vector {
  2. final int x, y;
  3. Vector(this.x, this.y);
  4. Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  5. Vector operator -(Vector v) => Vector(x - v.x, y - v.y);
  6. // Operator == and hashCode not shown. For details, see note below.
  7. // ···
  8. }
  9. void main() {
  10. final v = Vector(2, 3);
  11. final w = Vector(2, 2);
  12. assert(v + w == Vector(4, 5));
  13. assert(v - w == Vector(0, 1));
  14. }

If you override ==, you should also override Object’s hashCode getter.For an example of overriding == and hashCode, seeImplementing map keys.

For more information on overriding, in general, seeExtending a class.

noSuchMethod()

To detect or react whenever code attempts to use a non-existent method orinstance variable, you can override noSuchMethod():

  1. class A {
  2. // Unless you override noSuchMethod, using a
  3. // non-existent member results in a NoSuchMethodError.
  4. @override
  5. void noSuchMethod(Invocation invocation) {
  6. print('You tried to use a non-existent member: ' +
  7. '${invocation.memberName}');
  8. }
  9. }

You can’t invoke an unimplemented method unlessone of the following is true:

  • The receiver has the static type dynamic.

  • The receiver has a static type thatdefines the unimplemented method (abstract is OK),and the dynamic type of the receiver has an implemention of noSuchMethod()that’s different from the one in class Object.

For more information, see the informalnoSuchMethod forwarding specification.