Java inner class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.
Java inner classes are divided into 4 categories
- Static inner class
- Non-static java inner class
- Method local inner class
- Anonymous inner class
If the nested class is static, then it’s called static nested class.
- Static nested classes can access only static members of the outer class.
- Static nested class is same as any other top-level class and is nested for only packaging convenience.
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
Any non-static nested class is known as inner class in java.
- Java inner class is associated with the object of the class and they can access all the variables and methods of the outer class.
- Object of java inner class are part of the outer class object and to create an instance of inner class, we first need to create instance of outer class.
- Since inner classes are associated with instance, we can’t have any static variables in them.
OuterClass outerObject = new OuterClass();
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
If a class is defined in a method body,it’s known as local inner class.
- Since local inner class is not associated with Object, we can’t use private, public or protected access modifiers with it. The only allowed modifiers are abstract or final.
- A local inner class can access all the members of the enclosing class and local final variables in the scope it’s defined.
public void print() {
//local inner class inside the method
class Logger {
String name;
}
//instantiate local inner class in the method to use
Logger logger = new Logger();
}
A local inner class without name is known as anonymous inner class. An anonymous class is defined and instantiated in a single statement.
Anonymous inner class always extend a class or implement an interface. Since an anonymous class has no name, it is not possible to define a constructor for an anonymous class.
Anonymous inner classes are accessible only at the point where it is defined.
//anonymous inner class implementing FilenameFilter interface
String[] filesList = file.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.endsWith(ext);
}
});