Instance Variables

Instance variables are nothing more than variables declared inside a class.

 
class​ ComicsView {
 
ComicsCollection collection;
 
ComicModel model;
 
Element el;
 
// ...
 
}

In this case, we have declared three instance variables of different types. We could have declared all three as having a variable type (var collection, model, el;), but we are being good library maintainers by being explicit about the types.

Instance variables are accessible throughout the class with just their name—there is no need to prepend this. to a variable unless it would help to disambiguate an instance variable from a local variable.

By default, instance variables are public, which means they are accessible by subclasses and outside the class. For any public instance variable, Dart automatically creates an external getter and setter with the same name as the instance variable. For example, to access the comic book view’s collection, we can do this:

 
comics_view.collection;
 
// => instance of ComicsCollection

To switch the view to a new collection, we can do this:

 
comics_view.collection = new_collection;

Public instance variables are a nice convenience but should be used with caution if access control is needed.

Private Instance Variables

In some cases, public instance variables are a scary proposition. If a library does not want to expose an instance variable directly to its consuming context, then it can declare private variables. Private variables in Dart are simply variables that start with an underscore (for example, _models).

If, for example, we did not want to allow the collection to be changed, we could declare the collection as a private instance variable but still expose a public “getter.”

classes/private.dart
 
class​ ComicsView {
 
// Private because it starts with underscore
 
ComicsCollection _collection;
 
ComicsCollection ​get​ collection {
 
// possibly restrict access here...
 
return​ _collection;
 
}
 
}
Recipe 11Important: Private variables are only available in the library in which they are defined. If a subclass is defined in a separate library from its base class, then it cannot access instance variables in the superclass. Similarly, the superclass would not see private instance variables assigned in a subclass. This brings us to a very important rule: never access private instance variables between superclass and subclass. It may work when both are in the same library, but if they ever get refactored into separate libraries, bad things will happen. So don’t do it. We will run headlong into this restriction in Chapter 11, Project: Varying Behavior.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.176.5