1// example on inner class in java
2class OuterDemo
3{
4 int num;
5 // inner class
6 private class InnerDemo
7 {
8 public void display()
9 {
10 System.out.println("inner class");
11 }
12 }
13 // access inner class from method within
14 void printInner()
15 {
16 InnerDemo objInner = new InnerDemo();
17 objInner.display();
18 }
19}
20public class InnerClassExample
21{
22 public static void main(String[] args)
23 {
24 OuterDemo objOuter = new OuterDemo();
25 objOuter.printInner();
26 }
27}
1// example on static nested classes java
2import java.util.*;
3public class OuterClass
4{
5 static class NestedClass
6 {
7 public void display()
8 {
9 System.out.println("static nested class example");
10 }
11 }
12 public static void main(String[] args)
13 {
14 OuterClass.NestedClass nested = new OuterClass.NestedClass();
15 nested.display();
16 }
17}
1// example on method local inner class in java.
2class Outer
3{
4 // outer class instance method
5 void display()
6 {
7 int num = 96;
8 // method-local inner class
9 class MethodLocalInner
10 {
11 public void show()
12 {
13 System.out.println("in method local inner class " + num);
14 }
15 } // end of inner class
16 // access method local inner class
17 MethodLocalInner objInner = new MethodLocalInner();
18 objInner.show();
19 }
20 public static void main(String[] args)
21 {
22 Outer objOuter = new Outer();
23 objOuter.display();
24 }
25}
1// anonymous inner class as method argument.
2interface HelloWorld
3{
4 String print();
5}
6public class AnonymousInnerDemo
7{
8 // method accepts object of interface HelloWorld
9 public void display(HelloWorld m)
10 {
11 System.out.println(m.print() + "example of anonymous inner class as method argument.");
12 }
13 public static void main(String[] args)
14 {
15 AnonymousInnerDemo obj = new AnonymousInnerDemo();
16 // pass an anonymous inner class as an argument
17 obj.display(new HelloWorld() {
18 public String print() {
19 return "Hi! ";
20 }
21 });
22 }
23}
11. Can Outer class be static? --> No
22. Can inner class be static? --> Yes
33. Can you create an object from the inner class? --> Only if it's static
44. Can we have main method in inner class ? --> Only if it's static
55. Inner class can only be extended if it's static.