Inner classes in java
What is inner class?
Inner classes are classes defined within other classes.
Benefits of inner classes:
1. Special relationship:
An instance of inner class share with an instance of outer class, this special
relationship
gives code in the inner class access the members of outer class
even they are private.
2.More organizational
Using packages we can organize related classes. using inner classes we can provide more organizational separation.
3.Event handling
Inner classes are more useful for event handling, like button listener, text listener etc..
They are four ways you can define inner classes:
1. Inner classes
2. Method-local inner classes
3. Anonymous inner classes
4. Static nested classes
Inner classes:
This type is simple inner class, creating class directly into another class.
Applicable modifiers for inner class is
- final
- abstract
- public
- private
- protected
- strictfp
Example:
public class OuterClass {
private int x=10;
class Inner{
public void m1(){
System.out.println("Value of outer class member :"+x);
}
}
public static void main(String[] args)
{
OuterClass.Inner
inner = new OuterClass().new Inner();
//To create instance of an inner
class, you must have an instance of the
outer class
inner.m1();
}
}Output:
Value of outer class member :10
2.Method-Local inner classes:
Defining an inner class with in a method.
A method local inner class can instantiated only with in the method where the inner class is defined.Inner class object cannot use the local variables of that method. it is possible only when the variable is declared as final.
Applicable modifiers for method local inner class are
- abstract
- final
Example:
public class MethodLocal {
public static void m1(){
final int x=10;
class class2{
public void m2(){
System.out.println(x+"::i'm in
method local inner class");
}
}
class2
class2=new class2();
class2.m2();
}
public static void main(String[] args)
{
MethodLocal
methodLocal=new MethodLocal();
methodLocal.m1();
}
}