Inner classes, Method-Local Inner classes and Anonymous Classes
Inner Classes
Inner class is a member of an outer class. Inner class can access members of outer class. Inner class can also access private member of outer class.
Defining Inner class
Inner class are defined within the braces of outer class
Ex:
class Outer {
class Inner { }
}
Modifiers applied to Inner class are :
Private, Public, Protected
Final, Abstract, Strctfp
Instantiating an Inner class
Inner class can be accessed through the instance of outer class. To create an instance of inner class, instance of outer class must be created.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
class Outer { private int i= 9; class Inner { public void innerMethod() { System.out.println(“I is : “ +i); } } public static void main(String[] args) { Outer.Inner in = new Outer().new Inner(); in.innerMethod(); } } |
Output : I is 9.
Method-Local Inner Class
Inner class defined inside the method of any class called Method-Local Inner class. It can be instantiated only within the method where the Inner class is defined. Inner class defined inside the method must create an instance within the method but below the inner class definition.
Ex:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
class Outer { private int x = 6; void outerMethod() { class Inner { public void innerMethod() { System.out.println(“X is: “ +x); } } Inner in = new Inner(); in.innerMethod(); } } |
Modifiers applied to Method-Local Inner Class are Abstract and Final
Anonymous Inner Class
We can declare an inner class within the body of a method without naming it. These classes are known as anonymous inner classes.
Leave a Reply