Have you heard about Java Inner Class, but are not sure what it really means? Many people ignore Java Inner Classes in their learning journey, but they can make your Java programs better, cleaner, and easier to manage. Understanding Java Inner Classes can also help you write smarter and more organized code. If you skip it, you might miss an important part of Java programming that can make your life easier.
In this simple guide, you will learn what a Java Inner Class is, why it is important, and how to use Java Inner Classes with easy examples.
Table of Contents:
What is an Inner Class in Java?
An Inner class in Java is a type of class that is declared inside another class or interface. Java Inner classes allow one class to logically group related classes together, which improves the readability and maintainability of the code. These classes also have access to all the members of the outer class.
Syntax of Inner class:
class Java_Outer_class
{
//code
class Java_Inner_class
{
//code
}
}
Example:
Output:
Explanation: The above code first creates an object of the outer class. Then, it creates an object of the inner class using the outer class object. The display() function of the inner class is called, and it prints the outer class’s variable outerVar, which shows that the inner class can access the outer class’s variables.
Master Java Today - Accelerate Your Future
Enroll Now and Transform Your Future
Types of Inner Classes in Java
There are many types of Java Inner classes. Some of them are as follows.
1. Member Inner Class in Java
A Member Inner Class is a non-static class that is created inside a class, but outside a method, without using the static keyword. This means it is linked to the object of the outer class, and it can access all the members of the outer class. It is also known as a regular inner class. It can be declared with access modifiers like public, default, private, and protected.
To create an object of the member inner class, you first need an object of the outer class
Example:
Output:
Explanation: In this code, InnerClass is a member inner class inside OuterClass. It can directly access the private variable message. To create an object of InnerClass, we first create an OuterClass object. Then we call the display() method to print the message.
2. Anonymous Inner Class in Java
An anonymous inner class is an inner class that doesn’t have a name, and only a single object is created. It is used when you need to override a method of a class or an interface without making a separate subclass. It is created and used at the same time.
In simple words, a class that has no name is known as an anonymous inner class in Java. A Java Anonymous inner class can be created in two ways:
- By class (may be abstract or concrete).
- By interface
a. By Class
You can create an anonymous inner class by extending a class.
Here is the following example of creating an Anonymous inner class using a class.
Example:
Output:
Explanation: In this code, we created an object of an anonymous inner class that extends the Animal class. Then we override the sound() method. No separate class file is made; everything is taking place in one program.
b. By Interface
You can also create an anonymous inner class by implementing an interface.
Here is the following example of creating an Anonymous inner class using an interface.
Example:
Output:
Explanation: In this code, we created an object of an anonymous inner class that implements the Animal Interface. Then we override the sound() method inside it. No separate class file is made; everything is taking place in one program.
Get 100% Hike!
Master Most in Demand Skills Now!
3. Local Inner Class in Java
A class that is created inside a method is called a local inner class in Java. It can access the variables from the method if those variables are final or effectively final, meaning their values are not changed after they are first assigned.
Local Inner Classes are the inner classes that are defined inside a block.
Example:
Output:
Explanation: In this code, LocalInnerClass is created inside the show() method of OuterClass. It can access the local variable message because it is not changed after being assigned. Hence, the LocalInnerClass can be used inside the same method.
4. Static Nested Class in Java
A static nested class is a class that is created inside another class using the static keyword. They cannot access non-static data members and methods of the outer class. It can only be accessed by the outer class name. These Static Nested Classes can access static data members of the outer class, including the private members.
Note: A static nested class cannot access instance members of the outer class directly.
Example:
Output:
Explanation: In the code, StaticNestedClass is a static class inside OuterClass. It can access the static variable outerStaticVar. You can create an instance of StaticNestedClass without creating an OuterClass object. The display() method prints the static variable from the outer class.
5. Private Inner Class
In Java, unlike a regular class, an inner class can also be declared as private. A private inner class is a class that can only be accessed inside the outer class in which it is declared, no other class can see or use it from outside. This allows encapsulation of helper classes that are only relevant to the outer class.
In simple words, a private inner class is like a secret helper that only the outer class knows about.
Example:
Output:
Why Should We Use Inner Classes?
We need the Inner classes for the following reasons.
1. To access the Outer Class Variables:
- Inner classes are able to use all the variables of the outer class.
If it is a static nested class, it can only use the static variables and methods of the outer class.
2. To access the Local Variables:
- Classes inside a method can also use the local variables of the method, but if the variables are final or effectively final (meaning they don’t change after they are set).
Accessing the Private Members
One of the special characteristics of the inner classes in Java is that they can access the private variables and private methods of the outer class. This is allowed even if the private members are hidden from the other classes.
Because the inner class is tightly linked to the outer class, Java allows it to “see” everything inside the outer class, even its private things.
In simple words, an inner class can directly use private variables and call private methods of its outer class, just like it’s part of the same class.
Example:
Output:
Explanation: In the above Java code, InnerClass is defined inside the OuterClass. It can access a variable number and method privateMethod() from the outer class, because an inner class has special access to the members of the outer class.
Anonymous Inner Class as Argument
In Java, you can pass an anonymous inner class as an argument to a method. This is useful when you need to implement an interface or extend a class just for a single use. Instead of creating a separate class, you define and instantiate the class right in the method call.
Syntax:
methodName(new InterfaceName() {
// Implement methods here
});
- methodName is the name of the method you’re calling.
- InterfaceName or ClassName is the class or interface you are working or extending.
- Inside the curly braces, you provide the working of the methods you need to override.
Advantages of Using Inner Classes in Java
- Encapsulation: Inner classes can access private variables and methods of the outer class. This keeps the data hidden and in an organized manner. Encapsulation also makes the code easier to read and understand.
- Code Organization: By using inner classes, you can keep all the code together in one place. This makes the code clean and helps you find things in the code easily in the future.
- Better Access Control: The inner classes are made private, which means they can only be used inside the outer class. This adds protection to your code and takes care of the unwanted access.
- Callbacks: Inner classes are used to handle events, like button clicks. They make the event easy to define, without needing to create a separate class.
- Polymorphism: You can use inner classes to create different types inside the outer class. This way, you can easily create different behaviors of the methods in only one place using polymorphism.
Disadvantages of Using Inner Classes in Java
- Increases Complexity: If you are using inner classes more, your code can become harder to read and understand.
- Risk of Memory Leaks: If you are not careful with anonymous classes and non-static inner classes, you can accidentally cause memory leaks, which will make your program use more memory
Best Practices for Using Inner Classes
Let us discuss some of the best practices while using the Inner class in Java.
- Use Carefully: Inner classes make your code harder to understand, they should be only used when they make sense as part of the outer class.
- Accessing Outer Class Members: Inner classes can access all the parts of the outer class, even the private members. This is helpful when you want to keep all the code together.
- Static Nested Classes: If your nested class doesn’t need anything from the outer class’s instance (like variables or methods), it’s better to make it static.
- Keep It Simple: Always try to keep your inner classes as simple as possible, because if they get complex, they can make your main class harder to understand and work
- Use Wisely: You should use the inner classes only when they keep your code clear.
- Prefer Static Nested Classes When Possible: If your inner class does not want access from the outer class object, make it static.
- Be Careful with Memory: When using anonymous classes or local inner classes, be cautious of memory leaks. They create problems if you are not careful.
Unlock Your Future in Java
Start Your Java Journey for Free Today
Conclusion
Inner classes in Java are used to group classes. There are 5 types of Inner classes in Java: Member Inner Class in Java, Anonymous inner class in Java, Local inner class in Java, Static Nested Classes in Javaand Private Inner Class. They allow access to the private members of the outer class. However, they provide encapsulation and more advantages, they should be used carefully as they can lead to memory leaks and can make code complex
If you want to learn more about Java, you can refer to our Java Course.
Java Inner Class – FAQs
Q1. When should I use an inner class?
You should use an inner class when you want to define a class that is closely related to another class.
Q2. What is the final class in Java?
A class that cannot be further extended is called a final class in Java.
Q3. What is encapsulation in Java?
Encapsulation in Java means hiding data and only allowing access through methods.
Q4. How to call an inner class in Java?
To call the inner class in Java, you have to make an object of the outer class and then use the inner class.
Q5. What are the wrapper classes?
A Wrapper class in Java is one whose object wraps or contains primitive data types.