Reputation: 371
While going through A Tour of the Dart Language I see this example in the Constructors section:
class Point {
num x, y;
Point(num x, num y) {
// There's a better way to do this, stay tuned.
this.x = x;
this.y = y;
}
}
Talking about instances variables. Coming from Python this initially confused me a little as I though num x, y;
would be kind of class variables.
Does Dart have a concept of class variables?
Upvotes: 3
Views: 5884
Reputation: 657168
Not sure what you mean by "class variables".
I assume you mean static variables.
Static variables exist once per class, while instance variables exist once per instance.
class Point {
static num x, y;
fooMethod() {
print('$x, $y');
}
}
With in the class where they are declared, they can be accessed without a prefix. From everywhere else they are accessed using the lass name as prefix where they are declared.
void main() {
print(Point.x);
}
Also from subclasses the class prefix where the fields are declared are required because they are not inherited.
class CustomPoint extends Point {
barMethod() {
print('${Point.x}, ${Point.y}');
}
}
Upvotes: 6