Method

A method is a function that provides behaviors for an object, divided into four categories: instance methods, operator overloading, Getters/Setters, and abstract methods.

1. Instance methods

  1. Methods belonging to class instance objects;
  2. Can directly access instance variables and use the this keyword;
  3. Contains a complete function body for business calculations and logical operations.
import 'dart:math';

class Point {
  final double x;
  final double y;

  // Constructor initializes instance variables
  Point(this.x, this.y);

  // Instance method: Calculate distance between two points
  double distanceTo(Point other) {
    var dx = x - other.x;
    var dy = y - other.y;
    return sqrt(dx * dx + dy * dy);
  }
}

void main() {
  Point p1 = Point(0, 0);
  Point p2 = Point(3, 4);
  print(p1.distanceTo(p2)); // Output 5.0
}Code language: JavaScript (javascript)

2. Operators Overloading

  1. Most operators are essentially instance methods with special names;
  2. Declaration syntax: operator operatorSymbol(parameter) ReturnType { ... };
  3. List of supported overloadable operators:
    < > <= >= == ~
    - + / ~/ * %
    | ˆ & << >>> >>
    []= []
  4. Built-in operators cannot be overloaded (e.g. !=, automatically implemented by Dart at the underlying layer with no manual definition required);
  5. Overloading == requires overriding hashCode simultaneously; otherwise equality judgment will malfunction.
class Vector {
  final int x, y;

  Vector(this.x, this.y);

  // Overload + for vector addition
  Vector operator +(Vector v) => Vector(x + v.x, y + v.y);
  // Overload - for vector subtraction
  Vector operator -(Vector v) => Vector(x - v.x, y - v.y);

  // Overload == for equality comparison
  @override
  bool operator ==(Object other) =>
      other is Vector && x == other.x && y == other.y;

  // Matching override for hashCode
  @override
  int get hashCode => Object.hash(x, y);
}

void main() {
  final v = Vector(2, 3);
  final w = Vector(2, 2);

  assert(v + w == Vector(4, 5));
  assert(v - w == Vector(0, 1));
  print(v + w);
}Code language: JavaScript (javascript)

After overloading operators, we can perform arithmetic operations such as +, -, and == on two Vector objects just like we do with numeric values.

3. Getters and setters

  1. get: Read-only method to retrieve computed properties with no parameters;
  2. set: Write method to modify associated variables with exactly one parameter;
  3. All instance variables come with implicit getters; mutable variables include implicit setters;
  • Advantage: Ordinary variables can be converted to computed logic later without modifying external calling code;
  • Increment/decrement operators ++/-- invoke the getter only once and cache the value to avoid side effects.
    /// Rectangle for screen coordinate system; origin (0,0) at top-left corner
    class Rectangle {
      double left, top, width, height;
    
      Rectangle(this.left, this.top, this.width, this.height);
    
      // Getter: Calculate right boundary
      double get right => left + width;
    
      // Setter: Assign right boundary and update left reversely
      set right(double value) => left = value - width;
    
      // Getter: Calculate bottom boundary
      double get bottom => top + height;
    
      // Setter: Assign bottom boundary and update top reversely
      set bottom(double value) => top = value - height;
    }
    
    void main() {
      var rect = Rectangle(3, 4, 20, 15);
      assert(rect.left == 3);
    
      // Call setter
      rect.right = 12;
      assert(rect.left == -8);
      print(rect.left); // -8
    }Code language: JavaScript (javascript)

    4. Abstract methods

    1. Only defines an interface without a function body; a semicolon ; replaces the implementation;
    2. May only exist inside abstract class abstract classes or mixins;
    3. Subclasses must override and implement all abstract methods; otherwise the subclass must also be marked abstract.
    // Abstract class containing abstract methods
    abstract class Doer {
      // Abstract method: Declaration only, no implementation
      void doSomething();
    }
    
    // Concrete subclass required to implement all parent abstract methods
    class EffectiveDoer extends Doer {
      @override
      void doSomething() {
        print("Execute specific business logic");
      }
    }
    
    void main() {
      Doer worker = EffectiveDoer();
      worker.doSomething(); // Output: Execute specific business logic
    }Code language: JavaScript (javascript)

    Comparison

    Method TypeCore FeaturesSyntax MarkerUsage Scenarios
    Instance MethodAccess instance variables, complete logic bodyStandard function definitionRegular object behaviors (calculations, business operations)
    Operator OverloadingSpecial-named instance method with operator keywordoperator +() etc.Custom addition, subtraction, indexing and equality judgment for objects
    Getter/SetterRead/write properties; get has no params, set has one paramget / setEncapsulate computed properties, unified external read/write entry
    Abstract MethodNo method body, interface declaration onlySemicolon ; after method signatureAbstract parent class defines specifications, enforces subclass implementation

    Leave a Reply

    Your email address will not be published. Required fields are marked *