Static Class and Its Usage in Java Example Program
Static Class (Nested) Characteristics In Java
- A static class can access without creating any of object If it has static data members and methods.
- A static class cannot access non-static data members and methods.
- The static class can be accessed by outer class name.
- Need to create an object for access non-static data members and methods.
- A static class created inside a class is called nested static class.
- Only nested classes can be static classes.
- In Java, we can declare a class within another class. It is called a nested class. That nested class accessed based on Outer class.
Syntax
//Static Class
static class className(){
//Do something
}
//Static variable
static int variableName = 0;
//Static method inside a static class
static class className(){
static void staticMethod(){
//Do something
}
}
Static Class Example Program
class StaticClass {
public static class StaticClassInner {
public static int staticNumber = 100;
public static int staticMethod() {
staticNumber = 200;
return staticNumber;
}
}
public static void main(String []args){
System.out.println("Initial value of Static number : " + StaticClassInner.staticNumber);
System.out.println("Static number inside static class : " + StaticClassInner.staticMethod());
}
}
Sample Output
Initial value of Static number : 100
Static number inside static class : 200
Basic Programs
- My First Example Java Program
- Constructor Example Java Program
- Parametrized Method Example Java Program
- Static Class and Its Usage in Java Example Program
- Static Function or Method and Its Usage in Java Example Program
- Default and Parameterized Constructor Java Example Program
- Constructor Chaining Java Example Program
- Singleton Class Using Private Constructor Java Example Program
- Constructor Overloading Example Java Program
- Simple Class and Array of Object Java Example Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Create Matrix Example Java Program
- Sum Of Three Numbers Example Java Program
- Heap Sort Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program