DART PROGRAMMING
(OOP)
OBJECT ORIENTED PROGRAMMING
CLASSES
A class is a blueprint for creating objects. A class encapsulates data for the
object. Dart gives built-in support for this concept called class.
The class keyword is used to declare a class in Dart. The class definition
starts with the keyword class and followed by the class name and the class
body enclosed by a pair of curly braces.
Below is the syntax for defining a class:
class class_name{
<fields>
<getters/setters>
<constructor>
<methods>
}
Cont’d
The class definition can include the following:
Fields: A field is any variable declared in a class. Field represents data
pertaining to the objects. Example of a class with fields:
class Employee {
String name;
int age;
String address;
}
Note how I started the name of the class with an Uppercase, classes
name should start with Uppercase to follow the standard rule of
programming. However you can start your class name with lowercase.
Setters and Getters
We can use setters and getters in our class in order to set values to our fields or get values from the
fields. Below is an example:
class Employee{
String name;
String get name {
return name;
}
void set name(String value){
name = value;
}
}
From the above code you can tell that a setter and a getter is simply like functions, the difference
here is that before the function name we use the keyword set / get and the get function doesn’t
have a parenthesis() after the name of the function.
Constructors
A constructor is a function that has the same name as the class and gets called once an object of the
class is created. It is responsible for allocating memory for the object of the class. Syntax for
constructor:
class_name([parameters]){
}
Constructors can have parameters or no parameters. Default constructors do not have parameters.
Example code:
class Employee{
String name;
Employee(){
print(‘An employee object is created’);
}
}
The constructor defined here is a default constructor since it has not parameters defined.
Parameterized Constructor
You can also create a constructor having some parameters. These
parameters will decide which constructor will be called and which will
be not. Those constructors which accept parameters is known
as parameterized constructor. Example code:
Class Employee{
String name;
Employee(String message){
print(message);
}
}
Named Constructors
As we can’t define constructors with different names unless we
parameterized the constructor to make it look different, we can use
named constructors to solve this problem. Below is the syntax for
name constructors:
class_name.constructor_name(parameters){
// body of the constructor goes in here
}