Inner Classes In Java
Inner classes are classes that are defined within other classes. Inner classes became available with Java 1.1, there are 4 type of inner classes:
- Member inner classes
- Local inner classes
- Anonymous inner classes
- Static inner classes
Member Inner Classes
Syntex Of Member Inner Class
[access modifier] class Outer {
code...
[access modifier] class Inner {
code....
}
}
- You can have any number of inner class object inside outer class code.
- If both inner class and Outer class are public, then some other class can also create an instance of the inner class.
- No inner class objects are automatically instantiated with an outer class object.
- If the inner class is static, then static inner class can be instantiated without an outer class instance, otherwise, the inner class object must be associated with an instance of the outer class.
- Inner class code has free access to all elements of the outer class object that contains it, by name (no matter what the access level of the elements is), if the inner class has a variable with same name then the outer class's variable can be accesse like this: OuterClassName.this.variableName
- The outer class can access all the members of inner class including private.
Method Inner Class Example
class Outer {
int x, y;
Outer() {
x = 100;
y=200;
Inner obj = new Inner(); //creating inner class object
obj.show();
}
class Inner {
int x ;
Inner() {
x = 1000;
}
void show() {
System.out.println("Inside Inner Class Show "+(this.x+Outer.this.x)); //accessing inner as well as outer class variable
}
}
}
public class InnerDemo {
public static void main(String[] args) {
Outer obj = new Outer(); //creating outer class object
Outer.Inner inner=obj.new Inner(); // creating inner class object
// outside outer class
inner.show(); //invoking inner class method using
// inner class object
}
}
Output
Inside Inner Class Show 1100 Inside Inner Class Show 1100



