constructor
class Person { String name; int age; } void main() { var person = Person(); print('${person.name} ${person.age}'); // Output: null 0 }class Person { String name; int age; // Parameterized constructor Person(this.name, this.age); } void main() { var person = Person('Alice', 30); print('${person.name} ${person.age}'); // Output: Alice 30 }class Person { String name; int age; // Named constructor Person.guest() { name = 'Guest'; age = 18; } } void main() { var person = Person.guest(); print('${person.name} ${person.age}'); // Output: Guest 18 }class Singleton { static Singleton _instance; // Private constructor Singleton._(); factory Singleton.getInstance() { if (_instance == null) { _instance = Singleton._(); } return _instance; } } void main() { var instance1 = Singleton.getInstance(); var instance2 = Singleton.getInstance(); print(identical(instance1, instance2)); // Output: true (Both references point to the same object) }class Point { final int x; final int y; // Initializer list constructor Point(this.x, this.y) : assert(x >= 0), assert(y >= 0); } void main() { var point = Point(2, 3); print('Point: ${point.x}, ${point.y}'); // Output: Point: 2, 3 }class Circle { final double radius; // Constant constructor const Circle(this.radius); double get area => 3.14159265359 * radius * radius; } void main() { const Circle circle1 = Circle(5.0); const Circle circle2 = Circle(5.0); print(circle1.area); // Output: 78.539816339745 print(identical(circle1, circle2)); // Output: true (Both objects are the same) }
Last updated