Default Getters and Setters
Default Getters and Setters
About
- Implicit Accessors: Created automatically for all fields
- Field-like Syntax: Accessed like regular fields
- No Overhead: No performance penalty
- Uniform Access Principle: Same syntax for fields and getters
Main Topics
-
Basic Usage
-
Definition: Automatic generation
-
Example:
class Person { String name; // Default getter/setter } void main() { var p = Person(); p.name = 'Alice'; // Uses setter print(p.name); // Uses getter }
-
-
Final Fields
- Definition: Read-only access
- Example:
class Circle { final double radius; // Only getter }
-
Type Safety
-
Definition: Enforced by compiler
-
Example:
class Box { int size; } void main() { var b = Box(); b.size = 'text'; // Compile error }
-
-
Null Safety
- Definition: Non-nullable by default
- Example:
class User { String name; // Non-nullable }
-
Inheritance
-
Definition: Works with subclasses
-
Example:
class Animal { int age; } class Dog extends Animal { // Inherits age getter/setter }
-
How to Use
- Simple Fields: Use default accessors
- Read-only: Mark fields final
- Type Safety: Use type annotations
- Initialization: Required for non-nullables
How It Works
- Compilation: Generates accessors
- Access: Same as field access
- Optimization: Inlined by compiler
- Null Safety: Enforced statically
Example:
class Rectangle {
double width, height;
Rectangle(this.width, this.height);
}
void main() {
var rect = Rectangle(10, 20);
print(rect.width); // Default getter
rect.height = 30; // Default setter
}
Conclusion
Default getters and setters provide a clean, efficient way to access object state with field-like syntax while maintaining encapsulation. They’re ideal for simple properties that don’t require additional logic during access or modification.