Nested Classes explained
Quite often, we come across the term “Nested Class” in Java. It is a very common interview topic as well. So in this blog post, I will be explaining what a nested class is in Java. What is a Nested Class? As the word suggests, a nested Java class is a class which lies within another Java class. Consider the following code snippet: class OuterClass{class NestedClass{}} The class NestedClass is like any other member of the OuterClass . It has access to other members that is methods and variables of the OuterClass even if a member is a private member. On compiling this code snippet, the compiler creates two class files. One will be the OuterClass.class and the other will be the OuterClass$NestedClass.class . If you have more than one nested class, the compiler creates a separate class file for each one. However, each of them will be prefixed with the name of the enclosing class and the $ sign. Why do we need nested classes? The following are some reasons where you ...