Introduction
In this blog, we will discuss classes and objects in Dart. Like many other modern programming languages, Dart is also an object-oriented programming language that supports the usage of classes, objects, and many other object-oriented constructs. In the next section, we will study in-depth about classes in Dart.
Dart Classes
The class is a blueprint for creating objects in Dart. Classes are used to encapsulate data and the functions that perform operations on that data. A class can be thought to be a user-defined data type similar to the way there are primitive data types in Dart.
Feel free to refer to the blog Dart Data Types on the Coding Ninjas Website to read more about the various dart types that Dart supports.
Syntax of Class Declaration
The following is the syntax to declare a class in Dart. The keyword class is used to declare classes in Dart. The body of the class needs to be encapsulated between a pair of curly braces, i.e. {}. As discussed earlier, the body of the class contains the fields, the constructors and the relevant functions, including getters and setters that operate on these fields.
class your_class_name {
<fields>
<constructors>
<getters/setters>
<functions>
}
Example Program
The following is a sample program that declares a class named Ninja with three fields and one function. The keyword class is used to declare the class. We will see how to create an object for this class in the next section.
Code:
class Ninja{
String ninja_name = "John";
String batch_name = "A1";
int roll_no = 10;
void fetch_ninja_details(){
print("Ninja name: " + ninja_name);
print("Batch name: " + batch_name);
print("Roll no: ${roll_no}");
}
}