Java Inner Class is defined inside the body of another class. Java inner class can be declared private, public, protected, or with default access whereas an outer class can have only public or default access.
Basic Points of Inner Classes :
- Inner Classes represent a special type of relationship that is it can access all the data members and methods of outer class including private.
- Inner Classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
- Code Optimization requires less code to write.
Types of Inner Classes
- Nested Inner Class
- Static Nested Classes
- Anonymous Inner Classes
- Method Local Inner Classes
Java Inner Classes
package com.jst;public class OuterClass {
int x = 25;
class InnerClass {
int y = 15;
}
}
package com.jst;
public class InnerExample {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.y + outer.x);
}
}
Output :
40Nested Inner Class
package com.jst;public class OuterClass {
class InnerClass {
System.out.println("Nested Inner Class Example");
}
}
package com.jst;
public class InnerExample {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.show();
}
}
Output :
Nested Inner Class ExampleStatic Inner Class
package com.jst;public class OuterClass {
int x = 30;
static class InnerClass {
int y = 15;
}
}
package com.jst;
public class StaticInnerExample {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.y + outer.x);
}
}
Output :
15Private Inner Class
package com.jst;public class OuterClass {
int x = 30;
private class InnerClass {
int y = 15;
}
}
package com.jst;
public class PrivateInnerExample {
public static void main(String[] args) {
OuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
System.out.println(inner.y + outer.x);
}
}
Note : If you try to access a private inner class from an outside class, It will throw Error Message.
Output :
Error Message : OuterClass.InnerClass has private access in OuterClassOuterClass.InnerClass inner = outer.new InnerClass();