Site Search:

Nested Class Demo

<Back

This example demonstrated the usage of Static Nested Class, Inner Class, Local Class and Anonymous Class. It also shows the variable shadowing effect in InnerClass. The code demonstrated the syntax of instantiate the nested classes from outside the enclosing class.

OCPJP>cat OuterClass.java 
class OuterClass{
    
    private int a = 0;
    public int getA() {return a;}
    static class StaticNestedClass{
        private int a = 10;
        static void aMethod() {
            (new OuterClass()).a = 10;
            //a = 2; not allowed
        }
        
        void printA() {
            System.out.println(a);
        }
    }
    
    class InnerClass{
        int a = 13;
        void aMethod(int a) {
            a = 900;
            this.a = 15;
            OuterClass.this.a = 12;
            System.out.println("a = " +a);
            System.out.println("this.a =" + this.a);
            System.out.println("InnerClass.this.a =" + InnerClass.this.a);
            System.out.println("OuterClass.InnerClass.this.a =" + OuterClass.InnerClass.this.a);
            System.out.println("OuterClass.this.a =" + OuterClass.this.a);
        }
    }
    
    void aMethod() {
        class LocalClass{
            void aMethod() {
                a = 13;
            }
        }
        
        LocalClass lc = new LocalClass();
        lc.aMethod();
    }
    
    interface Sayhello{
        public abstract void say();
    }
    
    Sayhello s = new Sayhello() {
        public void say() {a = 30;}
    };
    
    public static void main(String...args) {
        AnotherClass a = new AnotherClass();
        a.aMethod();
    }
}

class AnotherClass{
    void aMethod(){
        OuterClass out = new OuterClass();
        OuterClass.StaticNestedClass sn = new OuterClass.StaticNestedClass();
        sn.printA();
        OuterClass.StaticNestedClass.aMethod();
        System.out.println(out.getA());
        OuterClass.InnerClass au = out.new InnerClass();
        au.aMethod(500);
        System.out.println(out.getA());
        out.aMethod();
        System.out.println(out.getA());
        
        OuterClass.Sayhello sh = out.s;
        sh.say();
        System.out.println(out.getA());
        
    }
}
OCPJP>javac OuterClass.java 
OCPJP>ls *.class
AnotherClass.class   OuterClass$InnerClass.class  OuterClass.class
OuterClass$1.class   OuterClass$Sayhello.class
OuterClass$1LocalClass.class  OuterClass$StaticNestedClass.class
OCPJP>java OuterClass
10
0
a = 900
this.a =15
InnerClass.this.a =15
OuterClass.InnerClass.this.a =15
OuterClass.this.a =12
12
13
30
OCPJP>java -version
java version "1.8.0_31"
Java(TM) SE Runtime Environment (build 1.8.0_31-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.31-b07, mixed mode)
OCPJP>