Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Static Nested Classes
2.1.
Example
3.
Inner Classes
3.1.
Java
4.
Comparison Between a Normal Class & a Static Nested Class
5.
Frequently Asked Questions
5.1.
Can static nested classes have non-static members?
5.2.
Why use an inner class instead of a separate class?
5.3.
How can an inner class access the outer class's members?
6.
Conclusion
Last Updated: Apr 3, 2024
Medium

Nested Class in Java

Author Pallavi singh
0 upvote
Master Power BI using Netflix Data
Speaker
Ashwin Goyal
Product @
18 Jun, 2024 @ 01:30 PM

Introduction

Nested classes in Java might sound complex, but they're really just a way of organizing your code. Think of it like keeping your study notes in different sections of a binder for easier access. Java allows you to create a class within another class, which can be very useful  for grouping together related components in a tidy, structured way. 

Nested Class in Java

In this article, we'll learn everything  about nested classes, focusing on static nested classes & inner classes, and how they compare to regular classes. 

Static Nested Classes

When we talk about static nested classes in Java, think of them as a static member of the outer class. Just like static methods & variables, these classes can access all the static members of the outer class, but they don't have access to the instance variables & methods directly.

Example

Imagine you have a class called OuterClass & inside it, you want to define a static nested class called NestedClass. Here's how you could set it up:

public class OuterClass {
    // Static variable of the outer class
    static int outerVariable = 100;
       // Static nested class
    static class NestedClass {
        void display() {
            // Can access the static variable of outer class
            System.out.println("Value of outerVariable: " + outerVariable);
        }
    }
}


To use this NestedClass, you'd create an instance of it in the following way:

public class TestNestedClass {
    public static void main(String[] args) {
        // Creating an instance of the static nested class
        OuterClass.NestedClass nestedObject = new OuterClass.NestedClass();
        nestedObject.display();  // This will print: Value of outerVariable: 100
    }
}


In this setup, NestedClass acts almost like a regular class that's been packaged inside another class for organizational purposes. It's a neat way to keep your code structured & grouped logically, especially when the nested class only makes sense in the context of its enclosing class.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Inner Classes

Inner classes are a part of nested classes but with a twist; they are non-static. This means they are closely linked to the instance of the outer class. Picture this: If the outer class is a house, the inner class is a room that can only be accessed when you're inside the house.

Here's how you can use an inner class in Java:

  • Java

Java

class OuterClass {

// Inner class

class InnerClass {

// The inner class can access all members of the outer class, even if they are declared private

public void display() {

System.out.println("Message from the inner class.");

}

}

}

public class Main {

public static void main(String[] args) {

// First, create an instance of the outer class

OuterClass outer = new OuterClass();

// Then, create an instance of the inner class

OuterClass.InnerClass inner = outer.new InnerClass();

// Now you can call the method of the inner class

inner.display();

}
}

Output

Message from the inner class.


In this example, InnerClass is defined within OuterClass. To create an instance of InnerClass, you first need an instance of OuterClass. This setup allows InnerClass to access all the members (including private ones) of OuterClass, making it useful for handling complex scenarios where the inner class needs to manipulate the outer class's members directly.

Comparison Between a Normal Class & a Static Nested Class

AspectNormal ClassStatic Nested Class
AccessibilityCan be accessed from outside the containing class using its name.Accessed using the outer class name, as it's a static member of the outer class.
Association with Outer ClassNo direct association. Acts independently of any other class.Associated with its outer class. Can access static members of the outer class even if it's private.
Use CaseUsed when you need a standalone functionality that isn't tied to any particular class.Ideal for grouping classes that are only used in one place, enhancing readability and maintainability.
Instance CreationCreated using the new keyword followed by the class name.Created using the outer class name followed by the new keyword and the nested class name.
Access to Outer Class MembersCannot directly access the members of another class unless through an object.Can access all static members of the outer class, including private ones.

Frequently Asked Questions

Can static nested classes have non-static members?

Yes, static nested classes can have non-static members. However, to access these members, you need to instantiate the static nested class.

Why use an inner class instead of a separate class?

Inner classes are used for logical grouping, to access the outer class's members easily, and for better encapsulation. They are handy when a class is useful to only one other class.

How can an inner class access the outer class's members?

An inner class has direct access to all the members (including private ones) of its outer class. It doesn't need any special syntax for this; it can just use the member names directly.

Conclusion

In this article, we've learned the concept of nested classes in Java, focusing on static nested classes & inner classes. We saw how static nested classes, similar to static members, don't require an instance of the outer class to be accessed & can help organize related classes. Inner classes, on the other hand, offer a closer relationship with the outer class, allowing direct access to its members and providing a tight encapsulation.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Previous article
Strong Number in Java
Next article
Type Casting in Java
Live masterclass