In Java, you can declare a class within another class. Such class is called nested or inner class. Nested class has three types, non-static nested class, static nested class, and anonymous nested class.
Non-static nested class
Non-static nested class can access both static and non-static members of the outer class, including private members.
Note
Non-static nested class needs an instance of the outer class to make an instance of the inner class.
Non-static value: 20
Static value: 10
Static nested class
A static class is a class that is created inside a class, is called a static nested class in Java. It cannot access non-static data members and methods. A static nested class or inner class is declared with the static
keyword, it cannot access non-static members in the outer class.
More about static nested class on Static nested class.
Anonymous nested class
An anonymous inner class in Java is a type of inner class that does not have a name and is tied to a specific use case. It is often used when you need to override methods of a class or an interface and want to avoid creating a separate named class for such a small use case or single use.
The nested anonymous class is inside the Main
class, there is no class
keyword neither the class name, that is why it is called an anonymous nested class. The anonymous class overrides the greet()
method, and it is only used once here in the Main
class, the anonymous nested class cannot be reused.
You can replace the interface with a concrete class or an abstract class.
When the Java program is compiled, the Greeting.class
, Main.class
, and Main$1.class
binary files will be produced by the compiler, the Main$1.class
is the compiled anonymous nested class. If you have multiple nested classes, there will be Main$2.class
, Main$3.class
, etc.
Work with Java lambda expression
In many cases, anonymous inner classes can be replaced with lambda expressions (After Java SE 8), especially when dealing with functional interfaces. A functional interface is interface with a single abstract method, lambda expressions provide a more concise way to implement these interfaces. You can rewrite the previous anonymous nested class with lambda expression.
You can learn more about lambda expression on Lambda Expressions.
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_DevelopmentProgramming_LanguagesJavaNested_ClassStaticStatic_Nested_ClassAnonymous_Nested_ClassLambda_Expression
Reference: