Definition
-class inside another class is called as nested class.
1- static nested class –
It’s is static class which is defined inside another class.
-
static nested class can’t access instance variable directly
2- non static class(Inner classes)
2.1- member class
-
It’s is class which is defined inside another class.
-
member class can access instance variable directly.
2.2- Local class
-
It’s is class which is defined and used inside the method another class.
2.3- Anonymous class
-
It’s is nameless class which is defined inside body of constructor call.
code samples are here
1-Program to create static nested class ‘SmallStatic’ inside Outer class StaticInner and then create object of static nested class ‘SmallStatic’.
package innerClasses; public class StaticInner { static class SmallStatic{ SmallStatic(){ System.out.println("i am from static class"); } } public static void main(String[] args) { StaticInner.SmallStatic static1=new StaticInner.SmallStatic(); } }
2- Program to create member class ‘SmallMember’ inside Outer class MemberOut and then create objec of member class ‘SmallMember’.
package innerClasses; public class MemberOut { <br />class SmallMember{ <br />SmallMember(){<br />System.out.println("i am called");<br />}<br />} <br />public static void main(String[] args) { <br />MemberOut.SmallMember member=new MemberOut().new SmallMember(); <br />} <br />}
3- Program to create Local class ‘SmMth’and create its object inside method ‘shw2’ of Outer class MethodLocOut.
package innerClasses; public class MethodLocOut { <br />void shw2(){ <br />class SmMth{ <br />SmMth(){<br />System.out.println("i am called"); <br />}<br />} <br />SmMth mth=new SmMth();<br />} <br />public static void main(String[] args) { <br />MethodLocOut mLI=new MethodLocOut(); <br />mLI.shw2(); <br />}<br />}
4- Program to create Anonymous class with constructor of Outer class AnonCls.
package innerClasses; public class AnonCls { void show(){ System.out.println("hiui"); } public static void main(String[] args) { AnonymousClss clss=new AnonymousClss(){ void show(){ System.out.println("hiii"); } }; clss.show(); } }