Monday, January 12, 2015

Static member classes and Non Static Member Classes in Java



How to implement a static member interface

package com.java2novice.nested.classes;
public class MyStaticMemberInterfaceTest
implements MyStaticMemberInterface.MyStaticInterface
{
     public void implementMe()
    {
        System.out.println("Hey I have implemented successfully!!!");
    }
    public static void main(String a[])
    {
        MyStaticMemberInterfaceTest msi = new MyStaticMemberInterfaceTest();
        msi.implementMe();
    }
}
class MyStaticMemberInterface
{
 public static interface MyStaticInterface
{
        public void implementMe();
    }
}

How to access top level class variables from static member classes

package com.java2novice.nested.classes;
public class MyStatMemClassAcsVars
{
public static String staticVar = "You can access me!!!";
private String privVar = "You cannot access me";
public static class ChildClass
{
 public void myMethod()
{
    System.out.println(staticVar);
    System.out.println(privVar);
        }
  }
 public static void main(String a[])
{
MyStatMemClassAcsVars.ChildClass cc = new                   MyStatMemClassAcsVars.ChildClass();
        cc.myMethod();
    }
}

Give an example of basic non-static member class

package com.java2novice.nested.classes;
public class MyBasicNonStaticMemberClass
{
public class ChildClass
{
 public void myMethod()
{
            System.out.println("Hey you have called me!!!");
        }
    }
 public ChildClass getInnerInstance()
{
        return this.new ChildClass();
    }
 public static void main(String a[])
{
        MyBasicNonStaticMemberClass mbn = new MyBasicNonStaticMemberClass();
        ChildClass cc = mbn.getInnerInstance();
        cc.myMethod();
    }
}

How to initialise non-static member (local class) class

package com.java2novice.nested.classes;
public class MyNonStaticMemberClassInstance
{
public static void main(String a[])
{
        ParentClass pc = new ParentClass();
        ParentClass.ChildClass cc = pc.getInnerInstance();
        cc.myMethod();
        ParentClass.ChildClass cc1 = pc.new ChildClass();
        cc1.myMethod();
    }
}
class ParentClass
{
 public class ChildClass
{
 public void myMethod()
{
       System.out.println("Hey you have called me!!!");
        }
    }
  public ChildClass getInnerInstance()
 {
        return this.new ChildClass();
    }
}

No comments:

Post a Comment