Static Method in Java
Static Method in Java
import java.io.*;
// instance variable
int b = 50;
void simpleDisplay()
{
System.out.println(a);
System.out.println(b);
}
// main method
public static void main(String[] args)
{
GFG obj = new GFG();
obj.simpleDisplay();
// Calling static method.
staticDisplay();
}
}
Output
40
50
40
Example 2: In both static and non-static methods, static methods are directly accessed.
// Java program to demonstrate that
// In both static and non-static methods,
// static methods are directly accessed.
import java.io.*;
// non-static method
void nonstatic()
{
// our static method can accessed
// in non static method
display();
}
// main method
public static void main(String args[])
{
StaticExample obj = new StaticExample();
Output
static number is 100
The methods can be accessed only using The method is only accessed by class
object reference. name.