Dart : Difference between static method and instance method

Dart : Difference between static method and instance method

·

2 min read

Instance method :

  • Instance methods are associated with an instance of a class. They have access to the instance's properties and can modify them.

  • These methods are invoked on an object of the class using dot notation.

  • Instance methods can be overridden in subclasses.

  • They can access instance variables and other instance methods directly.

  •   class MyClass {
        // Instance variables
        int myInt; // Example integer variable
        String myString; // Example string variable
    
        // Constructor
        MyClass(this.myInt, this.myString);
    
        // Instance method
        void printValues() {
          print('My integer value: $myInt');
          print('My string value: $myString');
        }
    
        // Another instance method
        void updateValues(int newInt, String newString) {
          myInt = newInt;
    
          myString = newString;
        }
      }
    
      void main() {
    
        MyClass myObject = MyClass(10, 'Hello');
    
        print('Initial values:');
    
        myObject.printValues(); 
    
        myObject.updateValues(20, 'World');
    
        print('\nUpdated values:');
    
        myObject.printValues(); 
      }
    
  •   Initial values:
      My integer value: 10
      My string value: Hello
    
      Updated values:
      My integer value: 20
      My string value: World
    
      Exited.
    

Static method :

  • static methods are members of the class rather than the class instance in Dart.

  • static methods can only use static variables and call the class's static
    method.

  • To access the static method, we don't need to create a class instance.

  • To make a method static in a class, we use the static keyword.

  • Instead of the object, the static methods are the member class.

  •   class MyClass {
        static int staticVar = 10;
    
        // Static method to access static variable
        static void printStaticVar() {
          print(staticVar);
        }
    
        int count = 0;
    
        void increment() {
          count++;
        }
      }
    
      void main() {
        print(MyClass.staticVar); // Accessing static variable directly
        MyClass.printStaticVar();
    
        var counter1 = MyClass();
        counter1.increment();
        print(counter1.count); // Output: 1
    
        var counter2 = MyClass();
        counter2.increment();
        print(counter2.count); // Output: 1 // Accessing static variable via static method
      }
    
  •   10
      10
      1
      1
    
      Exited.