The Wayback Machine - https://web.archive.org/web/20241110133400/https://www.geeksforgeeks.org/nested-classes-java/
Open In App

Nested Classes in Java

Last Updated : 26 Jul, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation and creates more readable and maintainable code.

  • The scope of a nested class is bounded by the scope of its enclosing class. Thus in the below example, the class NestedClass does not exist independently of the class OuterClass.
  • A nested class has access to the members, including private members, of the class in which it is nested. But the enclosing class does not have access to the member of the nested class.
  • A nested class is also a member of its enclosing class.
  • As a member of its enclosing class, a nested class can be declared private, public, protected, or package-private(default).
  • Nested classes are divided into two categories:
    1. static nested class: Nested classes that are declared static are called static nested classes.
    2. inner class: An inner class is a non-static nested class.

Syntax:

class OuterClass
{
...
    class NestedClass
    {
        ...
    }
}

d

Static nested classes

In the case of normal or regular inner classes, without an outer class object existing, there cannot be an inner class object. i.e., an object of the inner class is always strongly associated with an outer class object. But in the case of static nested class, Without an outer class object existing, there may be a static nested class object. i.e., an object of a static nested class is not strongly associated with the outer class object. As with class methods and variables, a static nested class is associated with its outer class. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference. They are accessed using the enclosing class name.

OuterClass.StaticNestedClass

For example, to create an object for the static nested class, use this syntax:

OuterClass.StaticNestedClass nestedObject =
     new OuterClass.StaticNestedClass();

Below is the implementation of the above method:

Java




// Java program to demonstrate accessing
// a static nested class
 
// outer class
class OuterClass {
    // static member
    static int outer_x = 10;
 
    // instance(non-static) member
    int outer_y = 20;
 
    // private member
    private static int outer_private = 30;
 
    // static nested class
    static class StaticNestedClass {
        void display()
        {
            // can access static member of outer class
            System.out.println("outer_x = " + outer_x);
 
            // can access private static member of
            // outer class
            System.out.println("outer_private = "
                               + outer_private);
 
            // The following statement will give compilation
            // error as static nested class cannot directly
            // access non-static members
            // System.out.println("outer_y = " + outer_y);
           
              // Therefore create object of the outer class
              // to access the non-static member
              OuterClass out = new OuterClass();
              System.out.println("outer_y = " + out.outer_y);
           
           
        }
    }
}
 
// Driver class
public class StaticNestedClassDemo {
    public static void main(String[] args)
    {
        // accessing a static nested class
        OuterClass.StaticNestedClass nestedObject
            = new OuterClass.StaticNestedClass();
 
        nestedObject.display();
    }
}


Output

outer_x = 10
outer_private = 30
outer_y = 20


Inner classes

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

There are two special kinds of inner classes :

  1. Local inner classes
  2. Anonymous inner classes

Java




// Java program to demonstrate accessing
// a inner class
 
// outer class
class OuterClass {
    // static member
    static int outer_x = 10;
 
    // instance(non-static) member
    int outer_y = 20;
 
    // private member
    private int outer_private = 30;
 
    // inner class
    class InnerClass {
        void display()
        {
            // can access static member of outer class
            System.out.println("outer_x = " + outer_x);
 
            // can also access non-static member of outer
            // class
            System.out.println("outer_y = " + outer_y);
 
            // can also access a private member of the outer
            // class
            System.out.println("outer_private = "
                               + outer_private);
        }
    }
}
 
// Driver class
public class InnerClassDemo {
    public static void main(String[] args)
    {
        // accessing an inner class
        OuterClass outerObject = new OuterClass();
       
        OuterClass.InnerClass innerObject
            = outerObject.new InnerClass();
 
        innerObject.display();
    }
}


Output

outer_x = 10
outer_y = 20
outer_private = 30


Comparison between a normal or regular class and a static nested class

S.No. Normal/Regular inner class Static nested class
1. Without an outer class object existing, there cannot be an inner class object. That is, the inner class object is always associated with the outer class object. Without an outer class object existing, there may be a static nested class object. That is, a static nested class object is not associated with the outer class object.
2. As the main() method can’t be declared, the regular inner class can’t be invoked directly from the command prompt. As the main() method can be declared, the static nested class can be invoked directly from the command prompt.
3. Both static and non-static members of the outer class can be accessed directly. Only a static member of an outer class can be accessed directly.


Previous Article
Next Article

Similar Reads

Break Any Outer Nested Loop by Referencing its Name in Java
A nested loop is a loop within a loop, an inner loop within the body of an outer one. Working: The first pass of the outer loop triggers the inner loop, which executes to completion. Then the second pass of the outer loop triggers the inner loop again. This repeats until the outer loop finishes. A break within either the inner or outer loop would i
2 min read
Difference Between Static and Non Static Nested Class in Java
Nested classes are divided into two categories namely static and non-static. Nested classes that are declared static are called static nested classes. Non-static nested classes are called inner classes. A class can either be static or non-static in java. So there is a lot of difference between making a class static or non-static. There are two kind
4 min read
Nested if in Java
Generally, if condition works like yes or no type. If the condition satisfies, it executes some block of code. Otherwise, it doesn't execute the code. Let us see the syntax of the simple if condition. Syntax : if( condition ){ statements ; }Nested if condition Nested means within. Nested if condition means if-within-if. Nested if condition comes un
2 min read
Java Program to List all Files in a Directory and Nested Sub-Directories
Prerequisites: File class Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem. Algorithm : Create a File object for the main directory.Get an array of files for the main directory.If array
4 min read
Java Nested Loops with Examples
A Nested loop means a loop statement inside another loop statement. That is why nested loops are also called "loop inside loop". Nested For loop for ( initialization; condition; increment ) { for ( initialization; condition; increment ) { // statement of inside loop } // statement of outer loop} Nested While loopwhile(condition) { while(condition)
3 min read
Flattening Nested Collections in Java
A stream is a sequence of objects that supports various methods that can be pipelined to produce the desired result. Stream is used to compute elements as per the pipelined methods without altering the original value of the object. And, flattening means merging two or more collections into one. Consider the below illustration where we have an array
4 min read
Nested try blocks in Exception Handling in Java
In Java , we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed onto a stack. Given below is an example of a nested try. In this example, the inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block)
3 min read
Nested Interface in Java
We can declare interfaces as members of a class or another interface. Such an interface is called a member interface or nested interface. Interfaces declared outside any class can have only public and default (package-private) access specifiers. In Java, nested interfaces (interfaces declared inside a class or another interface) can be declared wit
5 min read
Catching Base and Derived Classes as Exceptions in C++ and Java
An Exception is an unwanted error or hurdle that a program throws while compiling. There are various methods to handle an exception which is termed exceptional handling. Let's discuss what is Exception Handling and how we catch base and derived classes as an exception in C++: If both base and derived classes are caught as exceptions, then the catch
4 min read
Utility Methods of Wrapper Classes in Java
Prerequisite: Wrapper Classes The objective of the Wrapper class is to define several utility methods which are required for the primitive types. There are 4 utility methods for primitive type which is defined by the Wrapper class: 1. valueOf() method: We can use the valueOf() method to create a Wrapper object for a given primitive or String. There
4 min read
Why Java Interfaces Cannot Have Constructor But Abstract Classes Can Have?
Prerequisite: Interface and Abstract class in Java. A Constructor is a special member function used to initialize the newly created object. It is automatically called when an object of a class is created. Why interfaces can not have the constructor? An Interface is a complete abstraction of class. All data members present in the interface are by de
4 min read
Sorting Elements of Arrays and Wrapper Classes that Already Implements Comparable in Java
Java provides the Comparable interface to sort objects using data members of the class. The Comparable interface contains only one method compareTo() that compares two objects to impose an order between them. It returns a negative integer, zero, or positive integer to indicate if the input object is less than, equal to, or greater than the current
4 min read
Need of Wrapper Classes in Java
Firstly the question that hits the programmers is when we have primitive data types then why does there arise a need for the concept of wrapper classes in java. It is because of the additional features being there in the Wrapper class over the primitive data types when it comes to usage. These methods include primarily methods like valueOf(), parse
3 min read
Commonly Used Methods in LocalDate, LocalTime and LocalDateTime Classes in Java
Java provides the three most important classes related to dates namely LocalDate, LocalTime, LocalDateTime which makes the handling of dates in Java very easy as in order to use these classes, we need to import 'java.time' package which is main the main API for dates, times, instants, and durations. Illustration: 1. java.time.* // To include all cl
5 min read
Different Ways to Create the Instances of Wrapper Classes in Java
Wrapper Class a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Methods: We can use two ways to construct the instance of the Wrapper Classes Usi
5 min read
Random vs ThreadLocalRandom Classes in Java
The Random Class of the java.util package is used for generating a stream of pseudorandom numbers. It uses a 48-bit seed, which is amended by implementing a Linear Congruential Formula. The general form of a Linear Congruential Formula is an+1 = k * an + c (mod m) where a0 is the seed, a1, a2, ... an, an+1 are the random numbers and k, c, m are con
5 min read
Java - Divide the Classes into Packages with Examples
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
How to Create Different Packages For Different Classes in Java?
Let us first know what is a class and package in Java. Class in java is a model for creating objects. It means that the properties and actions of the objects are written in class. Properties are represented by variables and actions of the objects are represented by methods. So, a class contains variables and methods. The same variables are also ava
6 min read
How to Access Inner Classes in Java?
In Java, inner class refers to the class that is declared inside class or interface which were mainly introduced, to sum up, same logically relatable classes as Java is purely object-oriented so bringing it closer to the real world. It is suggested to have adequate knowledge access the inner class, first create an object of the outer class after th
3 min read
Different Types of Classes in Java with Examples
A class is a user-defined blueprint or prototype from which objects are created. It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order: Modifiers: A class can be public or has default accessclass keyword: class keyword is used to create a clas
11 min read
Method Overloading in Different Classes in Java
Methods of a class said to be overloaded if Both declared in the same class, orBoth inherited by a class, orOne declared and one inherited And have the same name but a different signature. Refer to this article, Different ways of Method Overloading in Java, for a basic understanding of method overloading. The below programs demonstrate the same. Ca
3 min read
Static Control Flow with Inherited Classes in Java
Before understanding the static control flow of a program, we must be familiar with the following two terms: Class loading: It refers to reading the .class file and loading it into the memory(JVM). Java loads classes dynamically, that is, classes are loaded on demand only when they are referred.Class initialization: It refers to executing and initi
6 min read
Java Unnamed Classes and Instance Main Methods
Java has introduced a significant language enhancement in Java Enhancement Proposal (JEP) 445, titled "Unnamed Classes and Instance Main Methods". This proposal aims to address the needs of beginners, making Java more accessible and less intimidating. Let's delve into the specifics of this proposal and understand how it simplifies the learning curv
7 min read
Access modifiers for classes or interfaces in Java
In Java, methods and data members can be encapsulated by the following four access modifiers. The access modifiers are listed according to their restrictiveness order. 1) private (accessible within the class where defined) 2) default or package-private (when no access modifier is specified) 3) protected (accessible only to classes that subclass you
1 min read
Private Constructors and Singleton Classes in Java
Let's first analyze the following question: Can we have private constructors ? As you can easily guess, like any method we can provide access specifier to the constructor. If it's made private, then it can only be accessed inside the class. Do we need such 'private constructors ' ? There are various scenarios where we can use private constructors.
2 min read
Primitive Wrapper Classes are Immutable in Java
In Java, an immutable class is a class (Integer, Byte, Long, Float, Double, Character, Boolean, and Short) which once created then its body can not be changed and the same applies to immutable objects which once created cannot be changed. Now the question arises that we do need the help of wrapper classes while dealing with primitive data types in
3 min read
Output of Java program | Set 15 (Inner Classes)
Prerequisite :- Local inner classes , anonymous inner classes 1) What is the output of the following java program? public class Outer { public static int temp1 = 1; private static int temp2 = 2; public int temp3 = 3; private int temp4 = 4; public static class Inner { private static int temp5 = 5; private static int getSum() { return (temp1 + temp2
3 min read
Types of Classes in Java
A class is a blueprint in the Java programming language from which an individual object can be built. In Java, we may declare a class by using the class keyword. Class members and functions are declared simply within the class. Classes are required for the creation of Java programs. The object-oriented paradigm (OOP) allows users to describe real-w
8 min read
Understanding Classes and Objects in Java
The term Object-Oriented explains the concept of organizing the software as a combination of different types of objects that incorporate both data and behavior. Hence, Object-oriented programming(OOPs) is a programming model, that simplifies software development and maintenance by providing some rules. Programs are organized around objects rather t
10 min read
Classes and Objects in Java
In Java, classes and objects are basic concepts of Object Oriented Programming (OOPs) that are used to represent real-world concepts and entities. The class represents a group of objects having similar properties and behavior. For example, the animal type Dog is a class while a particular dog named Tommy is an object of the Dog class. In this artic
11 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg