For example:
class _Foo {
String _var1;
String var2;
}
I always use public variable var2
because I think it's no point to make private variables when the class is already private, because you can not access private class anyway.
But I found many people use private variable _var1
. Is this just a personal preference? When the class is private, what is the point of private instance variable? If you can not access the private class, you can not access all of its instance variables regardless whether they are private or not. If you can access the private class in the same lib, then you can access its all instance variables regardless whether they are private or not.
Instance variables are declared with the keyword “private” by default. However, it is possible to make an instance variable public or protected. The value of an instance variable can be changed only within the method in which it is declared.
Instance variables are made private to force the users of those class to use methods to access them. In most cases there are plain getters and setters but other methods might be used as well.
Yes it is possible.
Instance variables are sometimes known as fields or properties. Unlike Java, Dart doesn't have the keywords public , protected , and private .
Making the class private doesn't make its members private and it doesn't make instances of that class inaccessible.
Assume
lib/private_class.dart
class Foo {
final _PrivateClass privateClass = _PrivateClass();
}
class _PrivateClass {
String publicFoo = 'foo';
String _privateBar = 'bar';
}
bin/main.dart
import 'package:so_53495089_private_field_in_private_class/private_class.dart';
main(List<String> arguments) {
final foo = Foo();
print(foo.privateClass.publicFoo);
// print(foo.privateClass._privateBar); // invalid because of ._privateBar
}
You can't declare variables or parameters of the type of a private class or extend or implement the class in another library or create an instance of that class, but otherwise there is not much difference.
So if the field is supposed to be hidden (internal state) to users of the API, then make the field private.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With