Yes, inner classes can have static declarations only when they are declared as static nested classes. A static nested class behaves like a regular class that is logically grouped inside another class and can contain static fields, methods, and initialization blocks. However, a non-static inner class cannot declare static members because it is tied to an instance of the outer class, while static members belong to the class itself rather than any object instance.
Key Points:
• Static nested classes can contain static variables, methods, and static blocks. • Non-static inner classes cannot declare static members (except compile-time constant fields such as static final constants). • A static nested class can be created without creating an object of the outer class. • Non-static inner classes require an instance of the outer class to be instantiated. • Static nested classes are commonly used when the nested class does not need access to the outer class instance members.
Example:
Consider a utility class inside a larger application. If the utility logic does not depend on the outer class object, making it a static nested class is more efficient and easier to use.
Code Example:
class Outer {
static class StaticNested {
static void display() {
System.out.println("Static method inside static nested class");
}
}
class Inner {
// Not allowed:
// static void display() { }
}
}
public class Test {
public static void main(String[] args) {
Outer.StaticNested.display();
}
}Interview Tip:
A concise interview answer is: "Only static nested classes can have static members in Java. Non-static inner classes cannot declare static methods or variables because they are associated with an instance of the outer class, whereas static members belong to the class level."