encapsulation
class Person { String name; // Public field void introduce() { print('My name is $name.'); } } void main() { var person = Person(); person.name = 'Alice'; // Accessing the public field person.introduce(); // Accessing the public method }class Person { String _name; // Private field Person(this._name); // Private field initialized through constructor void _printName() { print('My name is $_name.'); } void introduce() { _printName(); // Accessing the private method from within the class } } void main() { var person = Person('Alice'); person.introduce(); // Accessing the public method, which accesses the private method // person._name; // This would be an error as _name is private // person._printName(); // This would also be an error as _printName is private }
Last updated