Instance /Field Variables

We can access the instance variables with dot ( . )

By default instance variables are set to "null" . But from Dart 2.9 with null safety you can't do this . It will show you an error

void main() {
  
  
  
  var employee1 =   Employee();  // Creating employee1 object   
  
  var  employee2 =  Employee(); // Creating employee2  object 
  
  
  
  //Attribute <=> Instance Variable <=> Field Variable 
  
  
   // Setting the instance variable of employee1 object 
   
  employee1.id =1;
  employee1.name ="John Doe";
  employee1.position ="CTO";
  employee1.companyname ="B"; // Overwritting companyname "A"
  
  
  
  employee2.id =2;
  employee2.name ="Jane Doe";
  employee2.position ="CEO";
  
 // companyname for employee2 will be set to "A" , because we 
 // didn't set it, it take the default value from class 
  
  
  
  
}

class Employee{
  
  
  int id;
  
  String name;
  
  String position;  

  String companyname = "A" ;
  
  
  
}

In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance. An instance variable is similar to a class variable.[1] An instance variable is a variable which is declared in a class but outside of constructors, methods, or blocks. Instance variables are created when an object is instantiated, and are accessible to all the constructors, methods, or blocks in the class.

Last updated