Difference between static and non-static method in Java

UPDATED: 29 May 2015

There is significant difference between static and non-static methods in Java. We'll understand each difference with example.

Accessing static and non-static methods
  • static method can be accessed without creating instance of class. It is attached with class itself.
  • To access non-static method you have to create instance of class.
public class ExampleStaticMethod {
 
 /* static method `add` */
 public static int add(int x, int y){
    return x + y;
 }
 
 /* non-static method `subtract` */
 public int subtract(int x, int y){
    return x - y;
 }
 
 public static void main(String[] args) {
    int x = 10;
    int y = 20;
  
    /* Accessing static method without creating instance */
    System.out.println("Addition: "+ add(x, y));

    /* Accessing non-static method */
    ExampleStaticMethod objExampleStaticMethod = new ExampleStaticMethod();
    System.out.println("Subtraction: "+ objExampleStaticMethod.subtract(x, y));
 }
}

Accessing variables in static and non-static methods
  • You can't access non static variables inside static methods.
  • You can access static and non-static variables inside non-static methods.
public class ExampleStaticMethod {
 
 public int k = 40;
 public static int z = 30;
 
 /* static method `add` */
 public static int add(int x, int y){
    /* You can access `z` but you can't access `k` */
    return x + y + z;
 }
 
 /* non-static method `subtract` */
 public int subtract(int x, int y){
    /* You can access `z` and `k` */
    return x - y - z - k;
 }
 
 public static void main(String[] args) {
    int x = 10;
    int y = 20;
  
    /* Accessing static method without creating instance */
    System.out.println("Addition: "+ add(x, y));

    /* Accessing non-static method */
    ExampleStaticMethod objExampleStaticMethod = new ExampleStaticMethod();
    System.out.println("Subtraction: "+ objExampleStaticMethod.subtract(x, y));
 }
}

Method Override
  • You can't @Override static methods.
  • You can @Override non-static methods.
public class ExampleStaticMethod2 extends ExampleStaticMethod{
 
 /**
  * Can't Override static method `add`
  * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  *  The method add(int, int) of type ExampleStaticMethod2 must override or implement a supertype method 
  */
 //@Override
 //public static int add(int x, int y){
 // return x + y;
 //}
 
 /**
  * Can't Override static method `add`
  * Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  *  Cannot make a static reference to the non-static method add(int, int) from the type ExampleStaticMethod2
  */
 //@Override
 //public int add(int x, int y){
 // return x + y;
 //}
 
 /* Override non-static method `subtract` */
 @Override
 public int subtract(int x, int y){
    return x - y;
 }
}

Method Overload
  • static and non-static methods have same behavior for method overloading.


0 comments :