Why Do We Use Nested Classes In Java?

Here we will discuss Why We Use Nested Classes In Java? where the nested class is used for increasing the encapsulation and increase the readability of code or program. And as we know that to declare the class as static we need to have the class as a nested class.



Nested Class

Nested classes are the class inside the class where we use nested class to give it as static so that we can use the encapsulation and make use of data hiding which help in increasing readability.

The nested class can be defined as both static and non static.

To see how we can initialize the nested class and make use of it to declare it as static follow the example given below.

public class Enclosing {
    private static int x = 1;
    public static class StaticNested {

        private void run() {
            // method implementation
    public void test() {
        Enclosing.StaticNested nested = new Enclosing.StaticNested();

Here we can see how an outer class enclosing is having an inner class staticNested class which is static by nature and used for declaring a private method inside an inner static class which means it is purely static.

Whereas a nested static class can not have all the access modifiers there are limited access modifiers that could be used in static classes.

In fact, the inner class of a nested class can be non static also where the member of the class can have any access modifiers

To learn more about Why Do We Use Nested Classes In Java? at click here for learning more and learning.

Also, visit Java Tutorials to learn more about java and java problems to see the solutions of java problems that people faced during solving the problems of java.

To learn more about python visit Python’s list: What is the difference Between methods Append and Extend? and also learn about other programming languages here.


Leave a Comment

%d bloggers like this: