In Java, the 'static' keyword is used to denote members that belong to the class rather than to instances of the class. 'static' members are part of the class and not the instances of that class. This means you do not need to create an object of that class to use a 'static' member. The 'static' keyword can be used with variables, methods, and nested classes.
Static Variables:
A static variable, also known as a class variable, is a variable that belongs to the class rather than an instance of the class. This means there is only one copy of the static variable, and its value is shared among all instances of the class.
class MyClass
{
public static int myStaticVar;
}
Usage:
MyClass.myStaticVar = 100;
System.out.println(MyClass.myStaticVar); // Outputs: 100
Here, `myStaticVar` is a static variable. You do not need to create an instance of `MyClass` to use `myStaticVar`.
Static Methods:
A static method is a method that belongs to the class rather than an instance of the class. You can call a static method without creating an instance of the class.
class MyClass
{
public static void myStaticMethod()
{
System.out.println("This is a static method.");
}
}
Usage:
MyClass.myStaticMethod(); // Outputs: This is a static method.
Here, `myStaticMethod` is a static method. You do not need to create an instance of `MyClass` to call `myStaticMethod`.
Static Nested Classes:
In Java, we can also create static nested classes. These are like any other top-level class and should be used for logically grouping classes that are only going to be used in one place.
class MyClass
{
static class MyStaticNestedClass
{
//...
}
}
Usage:
MyClass.MyStaticNestedClass nestedObject = new MyClass.MyStaticNestedClass();
Here, `MyStaticNestedClass` is a static nested class. You do not create an instance of `MyClass` to create an instance of `MyStaticNestedClass`.