Difference between static (class) method and instance method in Java, and explain with code
In Java, methods can be categorized into two main types: instance methods and static (class) methods. Understanding the differences between these two types of methods is crucial for effective object-oriented programming.
Here’s a simple example to illustrate the differences:
class Example {
// Instance variable
private int instanceVariable;
// Constructor to initialize instance variable
public Example(int value) {
this.instanceVariable = value;
}
// Instance method
public void instanceMethod() {
System.out.println("Instance Method called. Instance Variable: " + instanceVariable);
}
// Static variable
private static int staticVariable = 0;
// Static method
public static void staticMethod() {
System.out.println("Static Method called. Static Variable: " + staticVariable);
}
// Static method to modify static variable
public static void incrementStaticVariable() {
staticVariable++;
}
}
public class Main {
public static void main(String[] args) {
// Calling static method without creating an instance
Example.staticMethod(); // Output: Static Method called. Static Variable: 0
// Creating an instance of Example
Example example1 = new Example(10);
example1.instanceMethod(); // Output: Instance Method called. Instance Variable: 10
// Calling static method to increment static variable
Example.incrementStaticVariable();
Example.staticMethod(); // Output: Static Method called. Static Variable: 1
// Creating another instance of Example
Example example2 = new Example(20);
example2.instanceMethod(); // Output: Instance Method called. Instance Variable: 20
// Static method can be called without an instance
Example.staticMethod(); // Output: Static Method called. Static Variable: 1
}
}
instanceVariable
is an instance variable that is unique to each instance of the Example
class.staticVariable
is a static variable shared among all instances of the Example
class.instanceMethod()
can access the instanceVariable
and prints its value. It can only be called on an instance of the class.staticMethod()
can access the staticVariable
and prints its value. It can be called without creating an instance of the class.incrementStaticVariable()
static method modifies the static variable.