Home »
Java Programs »
Java Static Variable, Class, Method & Block Programs
Java program to explain static class
It is possible to make a class static, but the only inner class can be declared as static. An Outer class can not be declared as static.
To make a class static, you have to use a static keyword before class keyword while declaring static class. Static classes are required when you want to create an object of the inner class to access their methods without creating an object of the outer class. With the help of the static inner class, you can directly create an object of the class.
Static Class with Non Static Method:
//Java program to demonstrate example of static class.
import java.util.*;
public class StaticClassExample {
static int a = 0;
//static class declaration
static class ClsInner {
//method of static class
public void dispMessage() {
a = 20;
System.out.println("Value of a: " + a);
}
}
//main()
public static void main(String[] s) {
//create object of static inner class
StaticClassExample.ClsInner objClsInner = new StaticClassExample.ClsInner();
objClsInner.dispMessage();
}
}
Output
Value of a: 20
Static Class with Static Method:
import java.util.*;
public class StaticClassExample {
static int a = 0;
//static class declaration
static class ClsInner {
//static method of static class
public static void dispMessage() {
a = 20;
System.out.println("Value of a: " + a);
}
}
//main()
public static void main(String[] s) {
//no need to create object
StaticClassExample.ClsInner.dispMessage();
}
}
Output
Value of a: 20
Java Static Variable, Class, Method & Block Programs »