I want to know is why java forbid static filed/method inside inner class
Because those inner classes are "instance" inner classes. That is, they are like an instance attribute of the enclosing object.
Since they're "instance" classes, it doesn't make any sense to allow static
features, for static
in meant to work without an instance in first place.
Is like you try to create an static/instance attribute at the same time.
Take the following example:
class Employee {
public String name;
}
If you create two instances of employee:
Employee a = new Employee();
a.name = "Oscar";
Employee b = new Employee();
b.name = "jcyang";
It is clear why each one has its own value for the property name
right?
The same happens with the inner class, each inner class instance is independent of other inner class instance.
So if you attempt to create a counter
class attribute, there is no way to share that value across two different instances.
class Employee {
public String name;
class InnerData {
static count; // ??? count of which ? a or b?
}
}
When you create the instance a
and b
in the example above, what would be a correct value for the static variable count
? It is not possible to determine it, because the existence of the InnerData
class depends completely on each of the enclosing objects.
That's why, when the class is declared as static
, it doesn't needs anymore an living instance, to live it self. Now that there is no dependency, you may freely declare an static attribute.
I think this sounds reiterative but if you think about the differences between instace vs. class attributes it will make sense.