In Java, a static method is a method that belongs to a class rather than an instance of the class. This means that a static method can be called on the class itself, rather than on an object of the class. Static methods are commonly used for utility functions or methods that operate on class-level data.
To define a static method in Java, we use the static keyword in the method signature. Here’s an example:
public class MathUtils {
public static int add(int x, int y) {
return x + y;
}
}
public class Main {
public static void main(String[] args) {
int result = MathUtils.add(1, 2);
System.out.println(result); // Output: 3
}
}
In this example, we define a class called MathUtils with a static method called add() that takes two integers as arguments and returns their sum. We can then call the add() method on the class itself, rather than on an instance of the class.
Static methods cannot be overridden in Java. When a subclass defines a method with the same name and signature as a static method in its superclass, the subclass method hides the superclass method rather than overriding it. This means that if we call the method on an object of the subclass, the subclass method will be called, while if we call the method on an object of the superclass, the superclass method will be called.
Here’s an example to illustrate this:
public class Animal {
public static void makeSound() {
System.out.println("Animal is making a sound");
}
}
public class Dog extends Animal {
public static void makeSound() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Dog dog = new Dog();
animal.makeSound(); // Output: "Animal is making a sound"
dog.makeSound(); // Output: "Dog is barking"
Animal dogAnimal = new Dog();
dogAnimal.makeSound(); // Output: "Animal is making a sound"
}
}
In this example, we define a superclass called Animal with a static method called makeSound(), and a subclass called Dog that overrides the makeSound() method with a different implementation.
When we create an instance of Animal and call the makeSound() method, the Animal implementation of the method is called. When we create an instance of Dog and call the makeSound() method, the Dog implementation of the method is called.
However, when we create an instance of Dog and store it in a variable of type Animal, the makeSound() method of the Animal class is called, even though the object is actually an instance of Dog. This is because static methods are not overridden in Java, and the method is called based on the declared type of the variable rather than the actual type of the object.