When a class is decalared inside another class or interface is called inner class or nested class in java. The purpose of inner class is to group related classes together.
But in order to access the inner class (default inner class) or inner class members we have to create object of outer class first.
Let's check out a simple example:
class OuterClass{
int x = 10;
//inner class
class InnerClass{
int y = 20;
}
}
public class Main{ // file name
public static void main (String[] args) {
//create an object of OuterClass
OuterClass outer = new OuterClass();
//create an object of InnerClass
OuterClass.InnerClass inner = outer.new InnerClass();
//access the OutrrClass property
System.out.println("OuterClass property is "+outer.x);
//access the InnerClass property
System.out.println("InnerClass property is "+inner.y);
}
}
/**
* Output:
* OuterClass property is 10
* InnerClass property is 20
*/
>
# Private inner class
Inner class can be private, protected as well. When an inner class is private, it doesn't allow the outer class to access it's members. Means, provide restrictions over accessing the inner class members when it is private. Thus, you will get compile time error.
class OuterClass{
int x = 10;
//private inner class
private class InnerClass{
int y = 20;
}
}
public class Main{ // file name
public static void main (String[] args) {
//create an object of OuterClass
OuterClass outer = new OuterClass();
//create an object of InnerClass
OuterClass.InnerClass inner = outer.new InnerClass();
//access the OutrrClass property
System.out.println("OuterClass property is "+outer.x);
//access the InnerClass property
System.out.println("InnerClass property is "+inner.y);
}
}
Run, the about example. You will get the following error message in the console.
Main.java:15: error: OuterClass.InnerClass has private access in OuterClass
OuterClass.InnerClass inner = outer.new InnerClass();
^
# Static inner class
When inner class is static, it is possible to access the inner class properties without creating the object of outer class.
class OuterClass{
int x = 10;
//inner class
static class InnerClass{
int y = 20;
}
}
public class Main{ // file name
public static void main (String[] args) {
//create an object of InnerClass
OutrClass.InnerClass inner = new OuterClass.InnerClass();
//access the member of InnerClass
System.out.println("InnerClass property is "+inner.y);
}
}
/**
* Output:
* OuterClass property is 10
* InnerClass property is 20
*/
# Access the outer class members from inner class.
class OuterClass{
int x = 10;
//inner class
class InnerClass{
public int accessOuter(){
return x;
}
}
}
public class Main{ // file name
public static void main (String[] args) {
//create an object of OuterClass
OuterClass outer = new OuterClass();
//create an object of InnerClass
OuterClass.InnerClass inner = outer.new InnerClass();
//invoke the method
System.out.println("OuterClass property is "+inner.accessOuter());
}
}
/**
* Output:
* OuterClass property is 10
*/