In Java, a class declared within another class is called a nested class. A nested class can be declared as static or non-static.
Below is the syntax for declaring a nested class:
// Outer class - class enclosing another class
class OuterClass {
...
// (non-static) inner class
class InnerClass {
...
}
// static nested class
static class StaticNestedClass {
...
}
}
Like any other member of a class, a static or non-static nested class can be declared with either the private, public, protected, or default access modifier.
Non-static nested classes are also known as inner classes.
A
To instantiate an inner class, you need to first instantiate the outer class. Then, you can use the following syntax to create an inner class object.
Take a look at the code example below that demonstrates how inner classes are used.
class Calculator {private int result;public int getResult(){return result;}public void setResult(int result) {this.result = result;}class Adder {private int a;private int b;Adder(int a, int b) {this.a = a;this.b = b;}int sum () {return a + b;}}class Multiplier {private int a;private int b;Multiplier(int a, int b) {this.a = a;this.b = b;}int multiply () {return a * b;}}}public class Main {public static void main(String[] args) {Calculator calculator = new Calculator(); // instantiating the outer classCalculator.Adder myAdder = calculator.new Adder(5 , 10); // instantiating the inner classcalculator.setResult(myAdder.sum()); // result = 15System.out.println(calculator.getResult()); // prints 15Calculator.Multiplier myMultiplier = calculator.new Multiplier(5 , 10); // instantiating the inner classcalculator.setResult(myMultiplier.multiply()); // result = 50System.out.println(calculator.getResult()); // prints 50}}
Using inner classes in Java provides us the following benefits:
It improves code structure within your package, and it provides better encapsulation if you restrict its access to only one particular outer class by declaring the nested class as private.
Nested classes improve readability of your code, as you can enclose a number of small classes within a single outer class; thus, enabling you to place the code closer to where it is used.