To declare a Static class we need to have nested class, one single class cannot be declared static. To understand this let’s go through with the Top-level class or Outer Class and inner class.
Here we go…
Top-level classes:-
You declare a top-level class at the top level as a member of a package. Each top-level class corresponds to its own java file sporting the same name as the class name.
A top-level class is by definition already top-level, so there is no point in declaring it static; it is an error to do so. The compiler will detect and report this error.
Inner classes:-
You define an inner class within a top-level class.
Here we go with an example.
class MyStatic {
static class MyStaticInnerClass {
void innerClassObject() {
System.out.println("MyStaticInnerClass called");
}
}
}
class SecondClass {
static class MyStaticSecondInnerClass {
void secoundClassObject() {
System.out.println("MyStaticSecondInnerClass called");
}
}
public static void main(String[] args) {
MyStatic.MyStaticInnerClass objInnerClass = new MyStatic.MyStaticInnerClass();
SecondClass.MyStaticSecondInnerClass objSecondClass = new SecondClass.MyStaticSecondInnerClass();
objInnerClass.innerClassObject();
objSecondClass.secoundClassObject();
}
}
When we execute this code, we'll get below messages.
MyStaticInnerClass called
MyStaticSecondInnerClass called
No comments:
Post a Comment