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:

  • new is the keyword that is used to declare an instance of the class.
  • object_name is the object’s name.
  • class_name is the name of the class whose instance variable is being generated.
  • arguments are 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 Student
class Student {
// creating properties
String name;
String roll_number;
String course;
String level;
// Creating Function
void registerCourse()
{
print("$roll_number registered for CSC 101");
}
void record(){
print('$name with $roll_number is studying $course');
}
}
void main()
{
// Creating Instance of class
Student s1 = new Student();
//creating another object
Student s2 = new Student();
// Calling property roll_number and assigning value
// to it using object of the class student
s1.roll_number = '195HQ024';
s2.name = 'Maria';
s2.roll_number = '195HQ045';
s2.course = 'Computer science';
// Calling function
s1.registerCourse();
s2.record();
}

Free Resources