Classes And Objects

  1. Declaring a Class
  2. Classes in Dart are declared using the keyword class:

    class Person{
       /* ... */
    }

    The class declaration consists of the class name, the class header (specifying its type parameters, the primary constructor etc.) and the class body, surrounded by curly braces.
    Both the header and the body are optional: if the class has no body, curly braces can be omitted.

    class Person;

  3. Creating instances of classes
  4. After creating the class, we can create an instance or object of that class which we want to access its fields and functions.

    var p1 = Person();
    var p2 = Person();

    The following code has the same effect, but uses the optional new keyword before the constructor name:

    var p1 =new Person();
    var p2 =new Person();

    Version note: The new keyword became optional in Dart 2.


  5. Assessing Instance Variable and Function
  6. Objects have members consisting of functions and data (methods and instance variables, respectively). When you call a method, you invoke it on an object: the method has access to that object’s functions and data.
    Use a dot . to refer to an instance variable or method


    var p1 = Person();
    print ( p1.name );
    print ( p1.phone ):

  7. Examples

  8. import 'dart:math';

     

    class Point {

      double x;

      double y;

      double distance() {

        return sqrt(x * x + y * y);

      }

    }

     

    void main() {

      var a = Point();

      a.x = 2;

      a.y = 3;

      var b = Point();

      b.x = 4;

      b.y = 0;

      print(a.distance());

      print(b.distance());

    }



    3.605551275463989
    4.0


    //dart:core contains DateTime Object

    import 'dart:core';

     

    class Person {

      String name;

      int id;

      String phone;

      int yearOfBirth;

      int age() {

        return DateTime.now().year - yearOfBirth;

      }

      void printName() {

        print(name);

      }

    }

     

    void main() {

      var p1 = Person();

      p1.name = "Tom Vardy";

      p1.yearOfBirth = 1987;

      print(p1.age());

      p1.printName();

    }



    33
    Tom Vardy


    Note:

    All uninitialized instance variables have the value null.