Static and Instance Methods in Java
In Java, a method can belong to the class itself or to an object created from that class. Class-level methods are called static methods; object-level methods are called instance methods.
Static Methods
A static method belongs to the class. It can be called using the class name, without creating an object.
Example 1: Calling a Static Method
class StaticMethodDemo {
// Static method belongs to the class
static void greet() {
System.out.println("Welcome to Java");
}
public static void main(String[] args) {
// Same class: call directly
greet();
}
}
Output:
Welcome to Java
Explanation:
greet()is markedstatic, so it belongs to theStaticMethodDemoclass. No object is needed.- Because
main()is in the same class, we can call it directly asgreet(). - If the static method is in a different class, use that class name, for example
Utility.greet().
Example 2: Calling a Static Method from Another Class
class Utility {
static void greet() {
System.out.println("Welcome to Java");
}
}
class DifferentClassDemo {
public static void main(String[] args) {
// greet() belongs to Utility, not this class
Utility.greet();
}
}
Output:
Welcome to Java
Explanation:
greet()is declared in theUtilityclass.main()is insideDifferentClassDemo, so a directgreet()call would not work here.- We use
Utility.greet()to tell Java which class owns the static method.
Instance Methods
An instance method belongs to an object. Create an object with new, then call the method through that object.
Example 3: Calling an Instance Method
class InstanceMethodDemo {
// Instance method belongs to each object
void greet() {
System.out.println("Welcome to Java");
}
public static void main(String[] args) {
// Create an object, then call its method
InstanceMethodDemo obj = new InstanceMethodDemo();
obj.greet();
}
}
Output:
Welcome to Java
Explanation:
greet() is not static, so it is an instance method. The object obj is created first and then used to call the method.
Static vs Instance Methods
The table compares the two kinds of methods.
| Static method | Instance method |
|---|---|
| Belongs to the class. | Belongs to an object. |
| Called with the class name. | Called with an object. |
| Can directly access static members. | Can access both static and instance members. |
Explanation:
The main() method is static so Java can start the program without first creating an object.
Key Points:
- Static methods belong to a class and are called with the class name.
- Instance methods belong to objects and are called with an object.
- A static method cannot directly use
thisor instance variables.