Google's Dart - Properties


Introduction
Dart makes accessing properties easy. The following example illustrates four properties x,y,r and theta. Writing the keywords get and set make regular methods property methods. As of know Dart doesnot have keywords like private, public , protected. You can make a variable private by writing underscore in front of the variable's name. In our example _x and _y are private variables. These variables are not private to the class but to the library in which the class is declared. Even a subclass cannot access these variables if it is in a different library.  To position a class or a function in a library you use library directive. In our example we have used it as follows.

 #library("geometry");

To import a library you have to write

#import("somelibrary");

Dart also supports Scala like constructor. 

Point(this._x,this._y);


Program
#library("geometry");
void main() {
  print("Welcome to Dart's Properties");
  var v = new Point(12.0,5.0);
  print(v);
  v.x = 20.0;
  v.y = 30.0;
  print(v);
  v.r = 35.0;
  v.theta = 0.5;
  print(v);
}

class Point{
   double _x;
   double _y;
   Point(this._x,this._y);
   get r() => Math.sqrt(_x*_x + _y*_y);
   set r(double g) {
         double ta = theta;
         _x = g*Math.cos(ta);
         _y = g*Math.sin(ta);
   }
   get theta() => Math.atan(_y/_x);
   set theta(double g) {
     double ra = r;
     _x = ra*Math.cos(g);
     _y = ra*Math.sin(g);
   }
   get x() => _x;
   get y() => _y;
   set x(double g) => _x = g;
   set y(double g) => _y = g;
   toString(){
     return "radius = ${r} theta = ${theta} x = ${x} y = ${y}";
   }
}



Output
Welcome to Dart's Properties
radius = 13.0 theta = 0.39479111969976155 x = 12.0 y = 5.0
radius = 36.05551275463989 theta = 0.982793723247329 x = 20.0 y = 30.0
radius = 35.0 theta = 0.5 x = 30.71538966616305 y = 16.779893851147104

Comments

Popular posts from this blog

Harikavach ( Level 3 )

Potter Metaphor.

Grapes a Metaphor