CJ Inner Classes
CJ Inner Classes
Java inner class or nested class is a class that is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place to be more readable and
maintainable.
Additionally, it can access all the members of the outer class, including private data members and
methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}
Advantage of Java inner classes:
Nested classes represent a particular type of relationship that is it can access all the members (data
members and methods) of the outer class, including private.
Nested classes are used to develop more readable and maintainable code because it logically group
classes and interfaces in one place only.
Code Optimization: It requires less code to write.
Java Member Inner class
A non-static class that is created inside a class but outside a method is called member inner class. It is
also known as a regular inner class. It can be declared with access modifiers like public, default,
private, and protected.
Java Member Inner Class Example
In this example, we are creating a msg() method in the member inner class that is accessing the
private data member of the outer class.
class TestMemberOuter1{
private int data=30;
class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
TestMemberOuter1 obj=new TestMemberOuter1();
TestMemberOuter1.Inner in=obj.new Inner();
in.msg();
}
}
Output: data is 30
The java compiler creates two class files in the case of the inner class. The class file name of the inner
class is "Outer$Inner". If you want to instantiate the inner class, you must have to create the
instance of the outer class. In such a case, an instance of inner class is created inside the instance of
the outer class.
Java anonymous inner class is an inner class without a name and for which only a single object is
created. An anonymous inner class can be useful when making an instance of an object with certain
"extras" such as overloading methods of a class or interface, without having to actually subclass a
class.