Java Programming Lab
Session 6
By : Dr. Amar Arora
USAR, GGSIPU-EDC
Inner Class
1. When a class is declared inside a class or interface its is called as Java inner class.
2. It is used to group classes and interfaces in one place to make more readable and maintainable code.
Advantages:
1. Inner class has access all the members (data members and methods) of the outer class, including private.
2. It leads to Code Optimization, as it reduces code size.
Types of Inner Class
1. Member Inner Class: When a class is created within class but outside method.
2. Local Inner Class: When a class is created inside a member function.
3. Static Inner Class: A static class created within a class. They are also known as nested class.
4. Anonymous Inner Class: When a class is created for implementing an interface or extending class and is created
without using name, the name of these classes are decide by compiler.
Interface OuterInterface{ void functionToOverride(); }
class OuterClass { ...
class InnerClass { … }
void memberFunctionLocalInnerInnerClass(){
class LocaIInnerClass { … }
}
void memberFunctionAnonInnerClass(){
OuterInterface objOuterInterface = new OuterInterface() { // This is the body of Anonymous Inner Class
@Override void functionToOverride(){ [Link](“Anonymous Inner Class”); }
};
[Link](); // This is the call to Anonymous Inner Class Function
}
static class StaticNestedClass {...}
public static void main(String args[]){
[Link] in = new OuterClass().new InnerClass(); //First Method to create Inner Class Object
OuterClass objOuterClass=new OuterClass(); //Second Method to create Inner Class Object
[Link] objInnerClass= [Link] InnerClass();
[Link] objStaticNestedClass=new [Link](); // Creating Object of Static Inner Class
}
Program to Execute
11. Make an Interface InterfaceCalculator and
implement the interface in Calcualtor to make sure all
the functions given in the design InterfaceCalculator
has been followed during implementation.
12. Make a class SeriesEnabledCalculator to
implement InterfaceSeriesEnabledCalculator which
inherits InterfaceCalculator and
InterfaceScientificCalculator.