How can you create classes in Dart?

Class and property in the Google Dart language.

Today I played with the new Google Dart language and I liked what I saw. Google calls it “Structured Web Programming” and it’s purpose is replacing Javascript as the primary scripting language in browsers.

One of the things I really miss in Javascript are proper classes. You can fake classes with functions but it is what it is. Not a Class (NaC). So in my example I rebuilt a C# class that we use a lot in our Silverlight training: ‘Employee’

The Employee class has a constructor that takes a Name (string) and Salary (double). It has a method RaiseSalary(double percentage) and a public property ‘Info’ that returns info about the employee.

Getting started

So let’s start by opening http://try-dart-lang.appspot.com/ in Chrome. I use Chrome 14.0.835.202.

Dart code

Let’s start with a main top level function main function:

main() {
print('Hello, Vera!');
}

Enter the code in the Dart editor and press the play button:

editor

Employee class

So here’s an example of a class with a public property in Dart:

class Employee{
String name;
double salary;

Employee(String name, double salary){
this.name=name;
this.salary=salary;
}

get Info()=> "Hello "+name+", your salary is €"+salary;

RaiseSalary(double percentage){
salary=salary+salary*percentage/100;
}
}
main() {
var emp=new Employee("Vera",4500.0);
print(emp.Info);
emp.RaiseSalary(6);
print(emp.Info);
}

That results in:

resultdart

This is just a small example but it’s a nice start with Dart. You can find the full Language specification on the Dart website. Happy coding!

Written by Loek van den Ouweland on 2011-10-11.
Questions regarding this artice? You can send them to the address below.