Inner Classes in Java
Inner class in java
- A class declared inside another class is known as nested classes in java.
- An inner class in java is a class that is declared inside of another class without static modifier.
- It is also commonly known as a non-static nested class in Java.
- It can access all members (variables and methods) of its outer class.
Types of Inner Classes
There are basically four types of inner classes in java.
1.Nested Inner Class / Member Inner Class
2.Method Local Inner Classes
3.Static Nested Classes
4.Anonymous Inner Classes
1.Nested Inner Class
- A non-static class that is declared inside a class is known as member inner class in Java.
- It is also known as regular inner class.
- It can be declared with access modifiers like public, default, private, and protected.
object creation of inner member/ nested inner class
Outer_class o = new Outer_class(); // (1)
Outer_class.Inner_class i = o.new Inner_class(); // (2)
2. Method Local Inner Classes
An inner class that is declared inside a method of the outer class is called method local inner class in Java.
- Declaration of method local inner class cannot use any access modifiers such as public, protected, private, and non-access modifiers such as static.
- We can also declare method local inner class in Java inside the constructor, static initializers, and non-static initializers.
Ex :
public class Outer
{
// Method
public void method_name()
{
class Inner
{
// Body for class Nested.
}
}
}
3. Static Nested Classes
- When an inner class is defined with a static modifier inside the body of another class, it is known as a static nested class in Java.
- Static nested classes are not technically inner classes. They are like a static member of outer class.
Ex :
public class Outer
{
// Static member class.
public static class Nested
{
// Body for class Nested.
}
}
4. Anonymous Inner Classes
- A nameless inner class is called anonymous inner class.
- Anonymous inner classes are declared without any name at all.
- Java anonymous inner classes are useful when we need only one object of the class.
They are created in two ways.
1. Anonymous inner class that extends a class
2. Anonymous inner class that implements an interface
Creation of object anonymous class
new<interface-name or class-name>(argument-list)
{
// Anonymous class body
}
When to use Anonymous Inner class in Java?
1. The main purpose of using an anonymous inner class in java is just for instant use (i.e. one-time usage).
2. An anonymous inner class can be used if the class has a very short body.
3. It can be useful if only one object of the class is required.
4. An anonymous inner class is the best suitable for GUI based applications to implement event handling.
Comments
Post a Comment