Skip to content
APPCITORThe Tech Blog
Esc

Java OOP – Java Inner Classes

August 25, 2020 2 min read

Java OOP – Java Inner Classes

Java inner class is a class which is declared inside the class or interface. It can be declared private, public, protected, or with default access whereas an outer class can have only public or default access. We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable. There are four types of inner classes.

  1. Regular Inner Classes (Member Inner Classes)
  2. Static Inner Classes (Nested Inner Classes)
  3. Local Inner Classes
  4. Anonymous Inner Classes

Regular Inner Classes

Here the object of inner class can access the object of outer class. But the object of outer class cannot access the object of inner class. Inner class is making for the purpose of outer class. We use the object of inner class in the outer class. Inside the main method you can call the inner class by the outer class.

If you use the “this” keyword as shown in the example, you can access only the inner class. If you use “Outer.this”, you can access only the outer class. We don’t use static variables or the static methods in regular inner classes.

Example:

Static Inner Classes

Here only a template is associated with the other template. An object is not associated with the other object. In static inner classes we use static variables and also static methods.

Example:

Local Inner Classes

A local inner class is a class which creates within a method. Method is running when the class is creating. We cannot create objects by using the name of local inner classes. If we want to access a variable of outer class inside the inner class, that variable should be “final”.

Example:

Anonymous Inner Classes

An anonymous inner class is a class created for implementing interface or extending class. Its name is decided by the java compiler. We can call the things of the outer class only by the methods and attributes of the anonymous inner class. If the outer class is an interface, the method that we override should be public.

Example:

These are the four types of inner classes you should study when you are using java OOP. Let’s meet from the next article.

Thank you.

Share this article

Keep reading