So now you know what a outer class is and that the nested class is located in the outer class.
You got 2 different nested classes, Click to see how they are used in Java:
- static nested classes = NOT the inner class
- non-static nested classes = inner class
Difference Static vs Non-Static
The difference is very easy. the non-static has acces to the whole class and the inner class has not.
Difference Nested and Outer Classes
The difference between nested and outer classes is that you could use every modifier for the nested class. Whereas you could only use the modifiers: public and the default modifier for the outer classes.
This is an overview what the modifiers in Nested Classes do
Class | Package | Subclass
Same Package |
Subclass
Different Package |
World | |
Public | Yes | Yes | Yes | Yes | Yes |
Protected | Yes | Yes | Yes | Yes | No |
No modifier/Default | Yes | Yes | Yes | No | No |
Private | Yes | No | No | No | No |
So you got the levels of folders: classes, packages, subclasses (in and out the package) and all packages aka the world.
And you got the modifiers (for a nested class): public, protected, default, private.
Sometimes you will read that the protected modifier has no more, because it can’t go out of the package if the subclass is in another package. That is not true. Here is an example where the subclass is in another package and the protected method could be used;
Run the class in package 2 and you will see that it works.