Dart Private and Public Members
Private and Public Members in Dart
In Dart, members (fields and methods) of a class can be either public or private. Dart does not have explicit keywords like public
, private
, or protected
(as in some other languages like Java or C++). Instead, Dart uses a naming convention to specify access control:
- Public members: By default, all members are public and can be accessed from anywhere in the code.
- Private members: Any member that starts with an underscore (
_
) is considered private to the library (i.e., the Dart file). Private members cannot be accessed directly from outside the library they are defined in.
Key Points:
- Public members can be accessed anywhere in the program.
- Private members are only accessible within the same Dart file (same library). If you try to access a private member from outside its file, you will get an error.
Example of Private and Public Members in Dart
Here is an example of how public and private members work in Dart:
Example Code:
Explanation:
Public Members:
String name;
is a public field. It can be accessed directly from outside the class (inmain()
), such asperson1.name
.void displayInfo()
is a public method. It can also be called directly from outside the class, likeperson1.displayInfo()
.
Private Members:
_age
is a private field. It starts with an underscore (_
), making it private to the library (i.e., the current Dart file). It cannot be accessed directly from outside the class (e.g.,person1._age
will result in an error)._celebrateBirthday()
is a private method. It also starts with an underscore and is only accessible inside thePerson
class.
Accessing Private Members:
- Private members like
_age
can be accessed inside the class using methods such ascelebrateBirthday()
, which internally calls the private_celebrateBirthday()
method. - A getter method (
getAge()
) is provided to safely access the value of the private_age
field from outside the class.
- Private members like
Output:
Summary of Public and Private Members:
Public Members:
- By default, members are public in Dart.
- Public members can be accessed from anywhere, including outside the class.
- Public fields and methods don’t have an underscore (
_
) prefix.
Private Members:
- Private members start with an underscore (
_
). - Private members are only accessible within the class or the library (Dart file) in which they are declared.
- To access private members externally, we usually provide getter or setter methods.
- Private methods cannot be directly called from outside the class.
- Private members start with an underscore (
Best Practices:
- Use private members to encapsulate internal state and implementation details.
- Expose necessary information and behavior through public methods or getter/setter methods.
- Private members help in data hiding and protect sensitive data from external modifications.