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
- Methods belonging to class instance objects;
- Can directly access instance variables and use the
thiskeyword; - 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
- Most operators are essentially instance methods with special names;
- Declaration syntax:
operator operatorSymbol(parameter) ReturnType { ... }; - List of supported overloadable operators:
< > <= >= == ~- + / ~/ * %| ˆ & << >>> >>[]= [] - Built-in operators cannot be overloaded (e.g.
!=, automatically implemented by Dart at the underlying layer with no manual definition required); - Overloading
==requires overridinghashCodesimultaneously; 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
get: Read-only method to retrieve computed properties with no parameters;set: Write method to modify associated variables with exactly one parameter;- All instance variables come with implicit getters; mutable variables include implicit setters;
++/-- 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
- Only defines an interface without a function body; a semicolon
;replaces the implementation; - May only exist inside
abstract classabstract classes or mixins; - 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 Type | Core Features | Syntax Marker | Usage Scenarios |
|---|---|---|---|
| Instance Method | Access instance variables, complete logic body | Standard function definition | Regular object behaviors (calculations, business operations) |
| Operator Overloading | Special-named instance method with operator keyword | operator +() etc. | Custom addition, subtraction, indexing and equality judgment for objects |
| Getter/Setter | Read/write properties; get has no params, set has one param | get / set | Encapsulate computed properties, unified external read/write entry |
| Abstract Method | No method body, interface declaration only | Semicolon ; after method signature | Abstract parent class defines specifications, enforces subclass implementation |
Previous: Primary Constructors