Java - Instance Method and Class Method

Type of Method

A class can have two types of methods: instance methods and class methods.

Instance methods are also called non-static methods.

Class methods are also called static methods.

An instance method implements behavior for the instances of the class.

An instance method can only be invoked by an instance of the class.

A static method implements the behavior for the class itself.

A class method always executes by a class.

Syntax

The static modifier is used to define a class method.

To create an instance method, do not use static modifier in a method declaration.

Example

The following are examples of declaring some static and non-static methods:

// A static or class method
static void aClassMethod() {
   // method's body goes here
}

// A non-static or instance method
void anInstanceMethod() {
    // method's body goes here
}

Rule

It is not allowed to refer to instance variables from inside a static method.

A static method can refer to only static variables.

An non-static method can refer to both static variables and non-static variables.

The following code demonstrates the types of class fields that are accessible inside a method.

Demo

public class Main {
  public static void main(String[] args) {
     System.out.println(MyClass.m);
     //from w  ww  .j a  va2s. co m
     MyClass.printM();
     
     MyClass myObject = new MyClass();
     
     System.out.println(myObject.n);
     myObject.printMN();
  }
}

class MyClass {
  static int m = 100; // A static variable
  int n = 200; // An instance variable

  static void printM() {
    System.out.println("printM() - m = " + m);
  }
  void printMN() {
    System.out.println("printMN() - m = " + m);
    System.out.println("printMN() - n = " + n);
  }
}

Result