Tutoriallearn.com

Easy Learning


Home

Search Tutoriallearn.com :



Java Static Method

  • A static method is defined by using the keyword 'static' in method definition as given below:
    static void function1 () // static keyword in the method definition
    {
    	
    }
    
  • Advantage of static method is that it can be called without any object variable.
  • Purpose of static method is to share common functionality among all instances of the class.

Example 1: Static Method

class staticexample {
	static a = 10;
	static  void display(){                // Static Method is defined
		System.out.println("a = "+ a);
	}
    static void main(String args[]){
		display();                        // Static Method is called
	}
}

Output

a = 10
  • In this example, the class staticexample consists of one static method display() .
  • Static method display () can be called without creating any object of the class.
  • If main() method is defined in another class, then the static method should be called using name of class.
  • See the following example:

Example 2: Static Method

class staticexample {
	static a = 10;
	static  void display(){
		System.out.println(a);
	}
}
class demostatic {                        
	static void main(String args[]){      // main() method is defined in another class
		staticexample.display();
	}
}

Output

a = 10

Explanation of the program

  • In this example, main() method is defined in another class named demoexample .
  • To call static method display() from main(), display() method must be qualified using name of the class.
  • Here display() method is called using class name staticexample .

Remember: There are some restrictions on static method which are listed below.

Restrictions on Static Method

  1. Static method can access only static variable.
  2. Static method can call only static method.
  3. Static method cannot refer to this or super keywords in any way.


© Copyright 2016-2025 by tutoriallearn.com. All Rights Reserved.