Types of classes in Java. Nested classes

Types of classes in Java

  • Top level class:
    • Abstract class
    • Final class (Finalized class)
  • Interfaces
  • Enum
  • Nested class:
    • Static nested class
    • Member inner class (Simple inner class)
    • Local inner class
    • Anonymous inner class

Nested classes. When do they apply

A class is called a nested class if it is defined inside another class. The nested class should only be created to serve the enclosing class. If the nested class is useful in any other context, it should become the top-level class. Nested classes have access to all (including private) fields and methods of the outer class, but not vice versa. Because of this permission, the use of nested classes results in some encapsulation violation.

There are four categories of nested classes:

  • Static nested class
  • Member inner class (Simple inner class)
  • Local inner class (Local class)
  • Anonymous inner class

Such categories of classes, with the exception of the first, are also called inner (Inner class). Inner classes are associated not with the outer class, but with an instance of the outer.

Each of the categories has recommendations for its application. If a nested class needs to be visible outside of a single method, or is too long to fit comfortably within a single method, and if each instance of such a class needs a reference to its enclosing instance, then a non-static inner class is used. If a reference to the enclosing class is not required, it is better to make such a class static. If a class is needed only within a method and it is required to create instances of this class only in this method, then a local class is used. And, if, moreover, the use of a class is reduced to using only in one place and there is already a type that characterizes this class, then it is recommended to make it an anonymous class.

What is a "static class"

It is a nested class declared using the static keyword. The static modifier does not apply to top-level classes.


Read also:


Comments

Popular posts from this blog

Methods for reading XML in Java

XML, well-formed XML and valid XML

ArrayList and LinkedList in Java, memory usage and speed