In this tutorial, we will write an inner class program in java. Before that, you should have knowledge on the following topic in Java.
Example of Inner class in Java
To demonstrate the example if Member inner Class in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class OuterClass { // inner class declaring as private private class InnerClass { public void displayInner() { System.out.println("Inner class Acceseed"); } } // method for accessing the inner class void displayingInner() { InnerClass in = new InnerClass(); in.displayInner(); } } public class Main { public static void main(String args[]) { // Instantiating the outer class OuterClass out = new OuterClass(); // Accessing the displayingInner method. out.displayingInner(); } } |
Output:
Inner class Acceseed
Example: Accessing static method of a static class in Java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public class OuterClass { void MethodOuter() { System.out.println("Outer Class Method"); class LocalClass //Local Inner class { void MethodInner() { System.out.println("Inner Class Method"); } } LocalClass c = new LocalClass(); c.MethodInner(); } public static void main(String args[]) { OuterClass o = new OuterClass(); o.MethodOuter(); } } |
Output:
I am Inner Class