« Back
import java.util.Arrays; public class InnerClassTesting { public static void main(String[] args) { OuterClass outer = new OuterClass(5,6,7,8); //static nested classes example OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass(); System.out.println(staticNestedClass.getName()); staticNestedClass.d=10; System.out.println(staticNestedClass.d); //inner class example OuterClass.InnerClass innerClass = outer.new InnerClass(); System.out.println(innerClass.getName()); System.out.println(innerClass); innerClass.setValues(); System.out.println(innerClass); //calling method using local inner class outer.print("Outer"); //calling method using anonymous inner class AnonymousInner inner = new AnonymousInner() { public void myMethod() { System.out.println("This is an example of anonymous inner class"); } }; inner.myMethod(); } } OuterClass.java public class OuterClass { private static String name = "OuterClass"; private int s; protected int t; int u; public int v; //OuterClass constructor public OuterClass(int s, int t, int u, int v) { this.s = s; this.t = t; this.u = u; this.v = v; } public int getI() { return this.s; } //static nested class, can access OuterClass static variables/methods static class StaticNestedClass { private int a; protected int b; int c; public int d; public int getA() { return this.a; } public String getName() { return name; } } //inner class, non-static and can access all the variables/methods of the outer class class InnerClass { private int w; protected int x; int y; public int z; public int getW() { return this.w; } public void setValues() { this.w = s; this.x = t; this.y = u; this.z = v; } @Override public String toString() { return "w=" + w + ":x=" + x + ":y=" + y + ":z=" + z; } public String getName() { return name; } } //local inner class public void print(String initial) { //local inner class inside the method class Logger { String name; public Logger(String name) { this.name = name; } public void log(String str) { System.out.println(this.name + ": " + str); } } Logger logger = new Logger(initial); logger.log(name); logger.log("" + this.s); logger.log("" + this.t); logger.log("" + this.u); logger.log("" + this.v); } } abstract class AnonymousInner { public abstract void myMethod(); }
OuterClass
10
OuterClass
w=0:x=0:y=0:z=0
w=5:x=6:y=7:z=8
Outer: OuterClass
Outer: 5
Outer: 6
Outer: 7
Outer: 8
×
Report a Problem:
Description:
Submit