Reputation: 2821
If I cannot create an instance of a static class, why I can instantiate a static inner class?
In the code bellow, Counter is a static inner class but it can be instantiated as if it was not:
public class Task {
static class Counter {
int counter = 0;
void increment() {counter++;}
}
public static void main(String[] args) {
Counter counter1 = new Task.Counter();
Counter counter2 = new Task.Counter();
counter1.increment();
counter2.increment();
counter2.increment();
counter2.increment();
System.out.println("counter1: " + counter1.counter);
System.out.println("counter2: " + counter2.counter);
}
}
If Counter was not a static class, it cound be instantiate using the following sintax:
Counter counter1 = new Task().new Counter();
Counter counter2 = new Task().new Counter();
But I cannot figure out the difference between these approaches in practical means.
Upvotes: 3
Views: 114
Reputation: 497
A static nested class does not have access to the non-static fields and methods of the class within which it is nested. A non-static nested class ('inner class') exists within an instance of the nesting class, so it has access to its non-static fields and methods.
Upvotes: 0
Reputation: 213223
In the code bellow, Counter is a static inner class but it can be instantiated as if it was not:
An inner class (whether it be static
or not) can be instantiated, just like a normal class can. Making a class static
only allows you to access it without creating instance of the enclosing class. Like you did in that code:
Counter counter1 = new Task.Counter();
Here you are creating an instance of Counter
. But since Counter
is a nested class (that is what we call a static inner
class), we have to access it like that. Task.Counter
is the fully qualified name of Counter
class (Add package there). In fact, since your main
method is in the Task
class only, you can directly use:
Counter counter1 = new Counter();
Now, for an inner class
(non-static), you can't access that class without any instance of the enclosing class. So to create an instance of Counter
, you first need an instance of Task
, like this:
Task task = new Task();
Counter counter = task.new Counter();
You can combine those statements into one like this:
Counter counter = new Task().new Counter();
In simple words, the difference is that, an inner class
has a reference to the enclosing instance associated with it, which a nested class
has no such reference.
Upvotes: 4