For working professionals
For fresh graduates
More
6. JDK in Java
7. C++ Vs Java
16. Java If-else
18. Loops in Java
20. For Loop in Java
45. Packages in Java
52. Java Collection
55. Generics In Java
56. Java Interfaces
59. Streams in Java
62. Thread in Java
66. Deadlock in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
77. JUnit Testing
80. Jar file in Java
81. Java Clean Code
85. Java 8 features
86. String in Java
92. HashMap in Java
97. Enum in Java
100. Hashcode in Java
104. Linked List in Java
108. Array Length in Java
110. Split in java
111. Map In Java
114. HashSet in Java
117. DateFormat in Java
120. Java List Size
121. Java APIs
127. Identifiers in Java
129. Set in Java
131. Try Catch in Java
132. Bubble Sort in Java
134. Queue in Java
141. Jagged Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
150. parseInt in Java
152. Abstraction in Java
153. String Input in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
163. Deque in Java
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
176. Square Root in Java
189. Javafx
Java is a powerful and versatile programming language that supports several concepts and features to improve code association and exemplification. Nested classes, also known as inner classes, are one such element. Nested classes provide a way to distinguish between classes that are included within other classes while also improving code organization and encapsulation. In this post, we'll delve deep into Java's nested class world to examine its advantages over standard classes as well as how they differ from them.
A class that is defined inside another class is referred to as being nested in Java. The term "external class" is commonly used to refer to the enclosing class that houses the nested class. The concept of nested classes promotes code reuse and viability and allows for the better association of related classes.
Let's begin by learning how to utilize inner classes in Java and their syntax. Inner classes are those that exist within an outer class and interact with members of that class, including private members. This access enables inner classes to encapsulate related functionality and provide a logical grouping of code.
Here's an example to illustrate the usage of an inner class:
public class OuterClass {
private int outerData;
public void outerMethod() {
// Accessing outerData from inner class
InnerClass inner = new InnerClass();
inner.innerMethod();
}
// Inner class definition
public class InnerClass {
public void innerMethod() {
outerData = 10; // Accessing outerData from inner class
System.out.println("Inner method called");
}
}
}
The 'InnerClass' in the example above is specified within the 'OuterClass'. The 'outerData' variable of the enclosing class can be accessed and changed by the 'innerMethod()' of the 'innerClass'.
Below listed are some of the advantages of Java Inner Classes:
1. Encapsulation and Readability: Inner classes help achieve better encapsulation by logically grouping related code. This improves code readability and reduces complexity.
2. Access to Enclosing Class Members: All members of the enclosing class, including private members, are accessible to inner classes. This makes it simple for the inner and outside classes to exchange information and functionality.
3. Organization of the Code: You may organize your code more hierarchically and formally by layering classes, which will make it simpler to traverse and maintain.
4. Listener interface implementation: Inner classes are frequently used in listener interface implementation, where the advantages of inner class in Java serves as the outer class's event listener.
The need for inner classes arises in situations where a class is closely related to another class and does not make sense to be used independently. It is possible to depict this close connection and condense the functionality of the outer class using inner classes.
Take a look at a 'LinkedList' class and its 'Node' class as an example. The 'Node' class is tightly integrated with the 'LinkedList' and doesn't appear to be used separately. By defining "Node" as an internal class of "LinkedList," we establish a close connection and characterize the use of Nodes within the "LinkedList" class.
Java's nested classes may be separated into two categories: inner classes and static nested classes. Both kinds of nested classes give users the ability to construct classes inside of other classes, but they differ significantly in terms of accessibility, affiliation with the surrounding class, and member access.
1. Static Nested Classes:
Instances of the outer class are not connected to static nested classes, which are specified using the 'static' keyword. They may be accessed via the outer class name and are mostly used to logically organize classes. Some important points to note about static nested classes are:
Example:
public class OuterClass {
private static int outerData;
public static class NestedClass {
public void nestedMethod() {
outerData = 10; // Accessing static member of the enclosing class
System.out.println("Nested method called");
}
}
}
The 'NestedClass' above is a static nested class in java with example that is contained within the 'OuterClass'. The 'outerData' variable, a static member of the enclosing class, is accessible via the 'nestedMethod()' function.
2. Inner Classes:
Inner classes, also known as non-static nested classes, are associated with an instance of the outer class in java. They can access both static and non-static members of the enclosing class. Some important points to note about inner classes are:
Example:
public class OuterClass {
private int outerData;
public void outerMethod() {
InnerClass inner = new InnerClass();
inner.innerMethod();
}
public class InnerClass {
public void innerMethod() {
outerData = 10; // Accessing member of the enclosing class
System.out.println("Inner method called");
}
}
}
In the above example, the `InnerClass` is an inner class within the `OuterClass`. The `innerMethod()` can access the `outerData` variable, which is a member of the enclosing class.
In summary, the main differences between nested classes and inner classes in Java are:
Basis | Nested Classes | Inner Classes |
Accessibility | Can be accessed from outside the enclosing class | Can only be accessed within the enclosing class or via an instance of the enclosing class |
Association | Not associated with an instance of the enclosing class | Tightly coupled with the enclosing class and associated with an instance of the enclosing class |
Access to Members | Can access only static members of the enclosing class | Can access both static and non-static members of the enclosing class |
Understanding these differences is crucial for choosing the appropriate type of nested class based on the specific requirements of your code.
There are two types of Nested Classes as listed below:
As previously explained, static nested classes in Java do not reference an example of the enclosing class and are declared using the 'static' keyword. They may be reached via the outer class name and are mostly used for the cohesive grouping of classes.
Inner classes are nested, non-static classes that interact with the members of the enclosing class. They may access both static and non-static members of the enclosing class and are connected to an example of the outer class.
Normal or regular classes and static nested classes in Java have a few key differences:
1. Accessibility: Static nested classes must be accessed inside the surrounding class or through an event of the enclosing class, as opposed to normal classes, which may be accessed from anywhere in the code.
2. Static vs. Non-Static: Normal classes are non-static naturally, while static nested classes are expressly proclaimed as static.
3. Access to Enclosing Class Members: Normal classes don't approach the members from the encasing class except if a reference to the enclosing class is unequivocally passed. On the other hand, nested static classes can access the static members of the surrounding class.
Java's nested classes offer a potent method for arranging code and improving encapsulation. We may build logical groups, boost code reuse, and increase code readability by layering classes. Understanding the kinds of nested classes and their disparities from normal classes is significant for composing perfect and viable code in Java.
In this blog, we investigated the idea of nested classes, examined their benefits, explained the need for inner classes, and contrasted them and regular classes. We likewise dug into the sorts of nested classes, including static nested classes and inner classes. By leveraging nested classes effectively, Java developers can build robust and modular applications.
1. Can a nested class be declared as private in Java?
Yes, a nested class can be declared as private in Java. It is necessary to get a private nested class inside the encasing class.
2. How may a Java nested class be demonstrated?
We need to make use of the following syntactic pattern to provide an example of a nested class:
OuterClass.NestedClass = new OuterClass().new NestedClass();
3. What is an anonymous inner class in Java?
An anonymous kind of inner class that lacks a name is known as an anonymous inner class. It is both specific and created simultaneously, typically as part of a method call or class creation.
4. Can a nested class access its parent class's private members?
Yes, both inner classes and static nested classes have access to the surrounding class' private members.
5. What distinguishes a nested class C++ from a nested class in Java?
In Java, nested classes are distinguished by their placement inside other classes and are connected to an illustration of the surrounding class. In C , nested classes are distinguished from other classes, but they are not inevitably linked to an instance of the surrounding class. While Java has both nested classes and inner classes, C introduces the concept of nested classes.
Take the Free Quiz on Java
Answer quick questions and assess your Java knowledge
Author
Talk to our experts. We are available 7 days a week, 9 AM to 12 AM (midnight)
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
1.The above statistics depend on various factors and individual results may vary. Past performance is no guarantee of future results.
2.The student assumes full responsibility for all expenses associated with visas, travel, & related costs. upGrad does not provide any a.