How to Access Inner Classes in Java?
Last Updated :
17 Jan, 2022
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 that create an object of the inner class. As the inner class exists inside the outer class we must instantiate the outer class in order to instantiate the inner class. Hence, to access the inner class, first create an object of the outer class after that create an object of the inner class.
So as we know there are multiple types of inner classes been up there in Java
Example 1:
Java
import java.io.*;
class Outer {
class Inner {
int num = 10 ;
}
}
class GFG {
public static void main(String[] args)
{
Outer obj1 = new Outer();
Outer.Inner obj2 = obj1. new Inner();
System.out.println(obj2.num);
}
}
|
Now let us propose another example demonstrating private inner class. As inner classes can be made private or protected, unlike “regular classes”. If an inner class is private it is impossible to access that class using an outside object.
Example 2:
Java
import java.io.*;
class Outer {
private class Inner {
int num = 10 ;
}
}
class GFG {
public static void main(String[] args)
{
Outer obj1 = new Outer();
Outer.Inner obj2 = obj1. new Inner();
System.out.println(obj2.num);
}
}
|
Output:
Now let us propose another example illustrating static inner class. As we know the inner class can be static. We can access static inner class without creating objects of the outer class.
Example 3:
Java
import java.io.*;
class Outer {
static class Inner {
int num = 10 ;
}
}
class GFG {
public static void main(String[] args)
{
Outer.Inner obj2 = new Outer.Inner();
System.out.println(obj2.num);
}
}
|
Share your thoughts in the comments
Please Login to comment...