Java Inner Classes (Nested Classes)

Java Inner Classes (Nested Classes)

Java Inner Classes (Nested Classes)

Java Inner Classes:

In Java, an inner class, also known as a nested class, is a class that is defined inside another class. Inner classes provide a way to logically group classes that are only used in one place, while also increasing encapsulation and reducing class clutter.

There are four types of nested classes in Java:

  • Static nested classes: These are nested classes that are declared static. They can access only static members of the enclosing class, but not non-static members. They are commonly used to encapsulate helper classes that are only used within the enclosing class. For example:
				
					public class Outer {
    private static int count;

    public static class Nested {
        public void incrementCount() {
            count++;
        }
    }
}

				
			
  • Non-static nested classes (inner classes): These are nested classes that are declared without the static keyword. They can access both static and non-static members of the enclosing class, and can also have their own members. They are commonly used to implement a helper class that is used only by the enclosing class. For example:
				
					public class Outer {
    private int value;

    public class Inner {
        public void setValue(int newValue) {
            value = newValue;
        }
    }
}

				
			
  • Local classes: These are nested classes that are defined inside a method or a block of code. They have access to the same scope as the enclosing code, but cannot be accessed outside of the block in which they are defined. They are commonly used to define a helper class that is used only in one method. For example:
				
					public class Outer {
    public void doSomething() {
        class Local {
            public void sayHello() {
System.out.println("Hello from local class.");
            }
        }
        Local local = new Local();
local.sayHello();
    }
}

				
			
  • Anonymous classes: These are nested classes that are defined without a name. They are commonly used to implement an interface or extend a class in-line, without creating a new named class. For example:
				
					public class Outer {
    public void doSomething() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
System.out.println("Hello from anonymous class.");
            }
        };
r.run();
    }
}

				
			

Inner classes provide a way to create more organized, encapsulated, and reusable code in Java. By grouping related classes together, we can reduce class clutter and make our code easier to understand and maintain.

Join To Get Our Newsletter
Spread the love