Curriculum
In Java, a static class is a class that has only static members (variables and methods) and cannot be instantiated. This means that you can use the static members of a static class without creating an instance of the class.
Here’s an example of a static class in Java:
public class MathUtils { private MathUtils() { // private constructor to prevent instantiation } public static int add(int a, int b) { return a + b; } public static int multiply(int a, int b) { return a * b; } }
In this example, the MathUtils
class has only static methods, add()
and multiply()
. The class also has a private constructor to prevent instantiation, since there is no need to create an instance of the class to use its static methods.
Here are some rules to keep in mind when working with static classes in Java:
new
keyword..
operator and the method or variable name. For example, to use the add()
method in the MathUtils
class, you would call MathUtils.add(3, 5)
.Overall, static classes can be useful in Java when you have a set of related utility methods or constants that do not require state to be stored. By making all members of the class static, you can use these methods and constants without creating an instance of the class, which can help to reduce memory usage and improve performance.