Dart Classes | Dart Object | Reference Variable

Dart Classes | Dart Object | Reference Variable

ยท

2 min read

  • Class we used for the define common feature , and after that we use the same class every time we need , if we try to write this separately then our code is going to much lengthier and also efficiently is very low but if we use class than our code execution can be faster. In simple terms we can say that class is he blueprint of object which make our work easy.

  • In this we use student name and roll number as a example.

  • Here, first we create one class called student and then we declare two variable in the function which is student and roll number apart from that we also create two function in student class and we call this class in main function, I have declare both the value as null that' s why use we " ? " sign to define the value null.

  • For calling class to in main function we can use new keyword which not mandatory in dart while in java we have to use new keyword whenever we want to call class in function, while in dart we can simply right " variable_name = class name(); " , for the declare the value we sue variable_name.Instance or Field Variable to define the value. same goes for the function we just write function name after variable name with " . " to call the function of class in main function .

void main() {

    var student1 = Student();         // One Object, student1 is reference variable
    student1.id = 01;
    student1.name = "Vinit";
    print("${student1.id} id is ${student1.name}");

    student1.study();
    student1.sleep();

    var student2 = Student();        // One Object, student2 is reference variable
    student2.id = 02;
    student2.name = "Jay";
    print("${student2.id} id is ${student2.name}");
    student2.study();
    student2.sleep();
}

// Define states (properties) and behavior of a Student
class Student {
    int? id ;             // Instance or Field Variable, default value is null
    String? name;          // Instance or Field Variable, default value is null

    void study() {
        print("${this.name} is now studying");
    }

    void sleep() {
        print("${this.name} is now sleeping");
    }
}

Did you find this article valuable?

Support Vinit Mepani by becoming a sponsor. Any amount is appreciated!

ย