Table of contents
Use
_
before variable name.Private instance variable exists at the library.
Example:
In this example, I have two dart files
private_var.dart
andtest.dart
.
private_var.dart
In
private_var.dart
, I define a library nameprivate_var
.Inside this library, there's a class
A
with a private instance variable_avar
and a methoddisplay()
that prints the value of_avar
.
test.dart
- In
test.dart
, I import theprivate_var.dart
library.
Then, I define a main()
function where I create an instance obj
of class B
.
Class B
extends class A
from the private_var.dart
library, so it inherits all of its members including the display()
method.
Output Explanation:
Despite
_avar
being a private variable, classB
can access it becauseB
inherits fromA
, and inheritance grants access to all visible members, including private ones.Thus, when
obj.display()
is called, it invokes thedisplay()
method inherited from classA
, which prints the value of_avar
.Since
_avar
is accessible within the same library (due to Dart's library-level privacy), there's no access violation.