Inner Classes In Java

  • Java Inner classes
  • Advantage of Inner class
  • Difference between nested class and inner class
  • Types of Nested classes

An inner class in Java, also known as a nested class, is a class that is defined within another class or interface.

Inner classes are utilized to group classes and interfaces together in a coherent manner, enhancing readability and maintainability.

Furthermore, it has the capability to reach all the attributes of the enclosing class, even private variables and functions.

Syntax of Inner class

Example

class Java_Outer_class{

 //code

 class Java_Inner_class{

  //code

 }

}

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:

  • Nested classes represent a particular type of relationship that is it can access all the members (data members and methods) of the outer class, including private.
  • Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
  • Code Optimization : It requires less code to write.
  • Need of Java Inner class

At times, it is necessary for users to create a class with restricted access from other classes. In such cases, encapsulating the class within other classes would be a favorable approach.

If all the class objects are a part of the outer object then it is easier to nest that class inside the outer class. That way all the outer class can access all the objects of the inner class.

  • What is the internal code generated by the compiler for member inner class?
  • What are the two ways to create an anonymous inner class?
  • Can we access the non-final local variable inside the local inner class?
  • How to access the static nested class?
  • Can we define an interface within the class?
  • Can we define a class within the interface?
  • Difference between nested class and inner class in Java

An inner class is a component of a nested class, with non-static nested classes commonly referred to as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes. The non-static nested classes are also known as inner classes.

  • Non-static nested class (inner class) Member inner class Anonymous inner class Local inner class
  • Static nested class
  • Member inner class
  • Anonymous inner class
  • Local inner class
Type Description
Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing an interface or extending class. TheJava compilerdecides its name.
Local Inner Class A class was created within the method.
Static Nested Class A static class was created within the class.
Nested Interface An interface created within class or interface.

Input Required

This code uses input(). Please provide values below: