Instance variables

Here’s how you declare instance variables:

  1. class Point {
  2. num x; // Declare instance variable x, initially null.
  3. num y; // Declare y, initially null.
  4. num z = 0; // Declare z, initially 0.
  5. }

All uninitialized instance variables have the value null.

All instance variables generate an implicit getter method. Non-finalinstance variables also generate an implicit setter method. For details,see Getters and setters.

  1. class Point {
  2. num x;
  3. num y;
  4. }
  5. void main() {
  6. var point = Point();
  7. point.x = 4; // Use the setter method for x.
  8. assert(point.x == 4); // Use the getter method for x.
  9. assert(point.y == null); // Values default to null.
  10. }

If you initialize an instance variable where it is declared (instead ofin a constructor or method), the value is set when the instance iscreated, which is before the constructor and its initializer listexecute.