Classes And Objects
- Declaring a Class
- Creating instances of classes
- Assessing Instance Variable and Function
- Examples
Classes in Dart are declared using the keyword class:
/* ... */
}
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.
After creating the class, we can create an instance or object of that class which we want to access its fields and functions.
var p2 = Person();
The following code has the same effect, but uses the optional new keyword before the constructor name:
var p2 =new Person();
Version note: The new keyword became optional in Dart 2.
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
print ( p1.name );
print ( p1.phone ):
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());
}
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();
}
Tom Vardy
Note:
All uninitialized instance variables have the value null.