Inner Class In Java
In Java, an inner class is a class that is defined inside another class. Inner classes are useful when you want to encapsulate one class inside another class, so that the inner class has access to the private members of the outer class.
There are four types of inner classes in Java:
Member inner class: A member inner class is defined at the member level of a class. It can access all members of the enclosing class, including private members.
Static inner class: A static inner class is a nested class that is declared as static. It can access only static members of the enclosing class.
Local inner class: A local inner class is defined inside a method or a block of code. It has access to the final local variables of the enclosing method or block.
Anonymous inner class: An anonymous inner class is a local inner class without a name. It is typically used for creating a single object of an interface or an abstract class.
Here's an example of a member inner class:
code with mohitpublic class OuterClass {
private int x = 10;
public class InnerClass {
public void printX() {
System.out.println(x);
}
}
}
In this example, InnerClass
is a member inner class of OuterClass
. It has access to the private member x
of OuterClass
.
To create an instance of the inner class, you first need to create an instance of the outer class, like this:
code with mohitOuterClass outer = new OuterClass();
OuterClass.InnerClass inner = outer.new InnerClass();
inner.printX(); // prints 10
Comments
Post a Comment