what is inner class in java

1 year ago 88
Nature

In Java, an inner class is a class that is declared inside another class or interface. Inner classes are used to group classes that belong together, which makes the code more readable and maintainable. They can access all the members of the outer class, including private members, and can be used to implement callbacks and event handlers. There are four types of inner classes in Java:

  • Member Inner Class: It is a non-static class that is defined at the member level of a class. It has access to all the members of the outer class, including private members.

  • Local Inner Class: It is a class that is defined inside a method of an outer class. It can access all the members of the outer class, including private members, and can be used to define callbacks for GUI code.

  • Anonymous Inner Class: It is a local inner class without a name. It is used to create an instance of a class that implements an interface or extends an abstract class.

  • Static Nested Class: It is a static class that is defined inside another class. It does not have access to the members of the outer class, and it can be used to group classes that are only used in one place.

Inner classes can be used to achieve encapsulation and improve code reusability. However, larger segments of code within a class might be better modeled or refactored as a separate top-level class, rather than an inner class.