top

Search

Java Tutorial

.

UpGrad

Java Tutorial

What is Nested Class in Java

Introduction

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.

Overview

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.

Java Inner 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'.

Advantages of Java Inner Classes

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.

Need for Java Inner Classes

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.

Difference between Inner Class and Nested Class in Java with Example

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:

  • Accessibility: The 'OuterClass.NestedClass' syntax may be used to obtain static nested classes from outside the enclosing class.

  • Relationship with Enclosing Class: Static nested classes don't interact with the instance members of the enclosing class since they aren't connected to an occurrence of the outer class. The static members of the enclosing class are accessible to them.

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:

  • Accessibility: Inner classes must be gotten inside the enclosing class or by means of a case of the enclosing class. The syntax structure for making an occasion of an inner class is 'OuterClass.InnerClass innerObject = outerObject.new InnerClass();', where 'outerObject' is a case of the enclosing class.

  • Association with Enclosing Class: Inner classes are firmly combined with the enclosing class and approach its occasion members, including private members. They can directly access and modify the instance variables of the enclosing class.

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.

Types of Nested Classes

There are two types of Nested Classes as listed below:

i) Static Nested Classes

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.

ii) Inner 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.

Comparison between Normal Classes and Static Nested Classes

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.

Conclusion

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.

FAQs

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.

Leave a Reply

Your email address will not be published. Required fields are marked *