Instance Variables & Instance Methods in Dart

Vinit MepaniVinit Mepani
1 min read
  • Instance variable is a variable which declared inside the class but outside any function.

  • Instance method is a method which declared inside the class but outside any function.

    • In below example we can see that we have crated on class called Student and inside the call we have declare two variable which is " Id and name ",

      This two variable called in instance variable.

    • While we create three function in this class which are study , sleep and Alldetails , this three function called Instance Method.

    • For calling the class we use object , here we have use student1 as object and we call this object to call class variable and method to get output.

void main() {


    //Using object to call
    var student1 = Student();         // One Object, student1 is reference variable
    student1?.id = 01;
    student1?.name = "Vinit";
    student1?.Alldetails();
    student1?.study();
    student1?.sleep();


}

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


    String? name;          // Instance Variable, default value is null


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

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

  //Instance Method
   void Alldetails()
  {
    print("$id is $name");
  }
}

0
Subscribe to my newsletter

Read articles from Vinit Mepani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vinit Mepani
Vinit Mepani

"Hello World, I'm Vinit Mepani, a coding virtuoso driven by passion, fueled by curiosity, and always poised to conquer challenges. Picture me as a digital explorer, navigating through the vast realms of code, forever in pursuit of innovation. In the enchanting kingdom of algorithms and syntax, I wield my keyboard as a magical wand, casting spells of logic and crafting solutions to digital enigmas. With each line of code, I embark on an odyssey of learning, embracing the ever-evolving landscape of technology. Eager to decode the secrets of the programming universe, I see challenges not as obstacles but as thrilling quests, opportunities to push boundaries and uncover new dimensions in the realm of possibilities. In this symphony of zeros and ones, I am Vinit Mepani, a coder by passion, an adventurer in the digital wilderness, and a seeker of knowledge in the enchanting world of code. Join me on this quest, and let's create digital wonders together!"