V
V
VarIzo2020-12-12 15:05:32
Dart
VarIzo, 2020-12-12 15:05:32

Why are private class properties still available in dart?

Good day.
While studying Classes in the Dart language, I came across a strange moment for me.

void main() {
  T t = T();
  t._name = "1";
  print(t._name);
  print("");
  t.name = "2";
  print(t.name);
}

class T{
  String _name;
  void set name(String n) => _name = "this is $n";

  String get name => "out $_name";
}


At the output we have

1

out this is 2


So declaring a property private with an underscore doesn't really make it private? As far as I remember in java, if the property is private, then everything, only getters and setters.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
H
HemulGM, 2020-12-12
@VarIzo

There are no special keywords (public; private; protected) in Dart, that is, access specifiers, so all identifiers are "public" by default. The issue of encapsulation is resolved by agreement: all members of the class whose name begins with an underscore "_" are considered private.

In other words: privacy is conditional

U
Umpiro, 2020-12-12
@Umpiro

It's not class privacy, it's library privacy. When using your code as a library, the _name variable will become unavailable.

N
Neonoviiwolf, 2020-12-12
@Neonoviiwolf

You wrote in one file, in this case there is such a moment, privacy works between files. Place the code in different files.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question