Inner class and nested Static Class in Java with Example

Inner class and nested static class in Java both are classes declared inside another class, known as top level class in Java. In Java terminology, If you declare a nested class static, it will called nested static class in Java while non static nested class are simply referred as Inner Class. Inner classes are also a popular topic in Java interviews. One of the popular question is difference between inner class and nested static class , some time also refereed as difference between static and non static nested class in Java. One of the most important question related to nested classes are Where should you use nested class in Java? This is one of the tricky Java question, If you have read Effective Java from Joshua Bloch than in one chapter he has suggested that if a class can only be useful to one particular class, it make sense to keep that inside the class itself  otherwise declare it as top level class. Nested class improves Encapsulationand help in maintenance. I actually look JDK itself for examples and if you look HashMap class, you will find that Map.Entry is a good example of nested class in Java. Another popular use of nested classes are implementing Comparator in Java e.g. AgeCompartor for Person class. Since some time Comparator is also tied with a particular class, it make sense to declare them as nested static class in Java.  In this Java tutorial we will see what is Inner class in Java, different types of Inner classes, what is static nested classand finally difference between static nested class and inner class in Java.
Read more »

0 Response to "Inner class and nested Static Class in Java with Example"

Posting Komentar