Static vs Instance methods in Java

Static Methods

  • Static methods are declared using a static modifier.
  • Static methods can not access instance methods and instance variables directly.
  • Static methods usually used for operations that do not require any data from an instance of the class (from this).
  • This keyword is the current instance of a class.
  • A method that does not use instance variables that method should be declared as a static method.

main is a static method and it is called by the JVM when it starts an application.

Static Method

package anote;

public class Main {
    public static void main(String[] args) {

        int result = Calculator.sum(3, 2);
        System.out.println(result);

        hello("world");
    }

    public static void hello(String word) {

        System.out.println("hello " + word);
    }
}

class Calculator {
    public static int sum(int a, int b) {
        return a + b;
    }
}

Static method do not require to create instance. Just called class name dot method name to access them.

Instance Methods

  • Instance methods belong to an instance of a class.
  • To use an instance method we have to instantiate the class first usually by using the new keyword.
  • Instance methods can access instance methods and instance variables directly.
  • Instance methods can access static methods and static variables directly.
package anote;

public class Main {
    public static void main(String[] args) {

        Car car = new Car();
        car.engineSound();
    }
}

class Car {
    //instance methods do not use static keywords
    public void engineSound() {
        System.out.println("www");
    }
}

Static or instance method?

Does it use any fields (instance variables) or instance methods?

  • if yes, instance method
  • if no, static method

Leave a Reply

Your email address will not be published.

ANOTE.DEV