Reputation: 53
To my knowledge, normally in Java, something that is static means you can't create an instance of it. But if that is the case, why can you create an instance of a static nested class? Doesn't that defeat the purpose of something being static?
Upvotes: 1
Views: 791
Reputation: 45309
To my knowledge, normally in Java, something that is static means you can't create an instance of it.
That's not right. static
is more "does not belong to any specific instance, but to the type/class itself".
Think of a static class in the context of the enclosing class. A static class is a static
member, meaning that the nested class is not tied to any particular instance of the enclosing class.
The implication of this is that you can create an instance of the nested class without having to create an instance of the outer class first.
Upvotes: 4
Reputation: 135
Imagine a situation where you have a method in your nested static class and you want to call that method.
Refer to this snippet below:
class OuterClass
{
// static nested class
static class StaticNestedClass
{
void display()
{
System.out.println("Static Nested Class Display Method");
}
}
static void display()
{
System.out.println("Outer Class Display Method");
}
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display(); // This calls the display() method of the static nested class
OuterClass.display(); // This calls the display() method of outer class
}
}
How will you access the display() of static nested class without creating an object of it. Java allows to create an instance of static nested class so that we can access the methods defined within that class.
Hope it helps!!!
Upvotes: 0
Reputation: 270980
something that is static means you can't create an instance of it.
That's not true. Not only can you not create instances of static fields, you can't create instances of non-static fields either, because it is a field, not a class.
static
just means that you don't need to create an instance of the surrounding class to access it. static
members belong to the class itself, instead of instances of that class.
With this definition, static classes makes total sense.
Instances of static classes can be created without creating instances of their outer class:
class Outer {
static class Inner {}
}
Outer.Inner obj = new Outer.Inner(); // no Outer instances created!
Whereas instances of non-static inner classes cannot:
class Inner {
class Outer {
}
}
Inner inner = new Inner(); // I have to create this instance, otherwise it wouldn't compile
Inner.Outer outer = inner.new Outer();
Upvotes: 0