‹‹ Previous
Next ››
Java Static Method
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
- Static method can access only static variable.
- Static method can call only static method.
- Static method cannot refer to this or super keywords in any way.
‹‹ Previous
Next ››