How to create classes and objects in Dart
Dart is an object-oriented programming language, which means it supports concepts like classes, objects, etc.
Classes
Classes are the blueprints of objects. A class is a blueprint from which a variety of objects can be created. All properties and methods of the class will be accessible to all objects.
Syntax for class declaration
class class_name {
// Body of class
}
Here, class is the keyword used to initialize the class.
The class_name is the name of the class. The body of the class will consist of properties, constructors, getters and setters, methods, etc.
Objects
Objects are instances of a class, and they are declared with the new keyword and the class name.
Syntax for object declaration
syntax:
var object_name = new class_name([ arguments ]);
Here:
newis the keyword that is used to declare an instance of the class.object_nameis the object’s name.class_nameis the name of the class whose instance variable is being generated.argumentsare the parameters that must be sent if a constructor is to be called.
To access the properties and methods of the class, we use the object’s name with the dot (.) operator.
// For accessing the property
object_name.property_name;
// For accessing the method
object_name.method_name();
Code
// Creating Class Studentclass Student {// creating propertiesString name;String roll_number;String course;String level;// Creating Functionvoid registerCourse(){print("$roll_number registered for CSC 101");}void record(){print('$name with $roll_number is studying $course');}}void main(){// Creating Instance of classStudent s1 = new Student();//creating another objectStudent s2 = new Student();// Calling property roll_number and assigning value// to it using object of the class students1.roll_number = '195HQ024';s2.name = 'Maria';s2.roll_number = '195HQ045';s2.course = 'Computer science';// Calling functions1.registerCourse();s2.record();}