Dart: Private Instance Variable

Dart: Private Instance Variable

  • Use _ before variable name.

  • Private instance variable exists at the library.


    Example:

  • In this example, I have two dart files private_var.dart and test.dart .

private_var.dart

  • In private_var.dart , I define a library name private_var .

    Inside this library, there's a class A with a private instance variable _avar and a method display() that prints the value of _avar.

test.dart

  • In test.dart , I import the private_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, class B can access it because B inherits from A, and inheritance grants access to all visible members, including private ones.

  • Thus, when obj.display() is called, it invokes the display() method inherited from class A, 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.