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}
1// Anonymous inner class in java
2abstract class Anonymous
3{
4 public abstract void display();
5}
6public class AnonymousInnerExample
7{
8 public static void main(String[] args)
9 {
10 Anonymous obj = new Anonymous() {
11 public void display() {
12 System.out.println("anonymous inner class example");
13 }
14 };
15 obj.display();
16 }
17}
1// how to access private members of a class.
2class OuterClass
3{
4 // outer class private variable
5 private int number = 56;
6 // inner class
7 public class InnerClass
8 {
9 public int showNumber()
10 {
11 System.out.println("showNumber() method of inner class.");
12 return number;
13 }
14 }
15}
16public class AccessPrivateMembers
17{
18 public static void main(String[] args)
19 {
20 OuterClass objOuter = new OuterClass();
21 OuterClass.InnerClass objInner = objOuter.new InnerClass();
22 System.out.println(objInner.showNumber());
23 }
24}