Java Inner class
In Java, an inner class is also known as nested class. Inner classes are part of nested classes. When a non-static class is defined in nested class then it is known as an inner class. It is defined inside the class or an interface. Inner classes are mostly used to logically group all the classes and the interface in one place, which makes the code more readable and manageable. Inner classes can access members of the outer class including all the private data members and methods.
Syntax:
class OuterClass
{
//code
class InnerClass
{
//code
}
}
Types of Nested classes
-
Non-static nested class
- Member inner class
- Anonymous inner class
- Local inner class
- Local inner class
Following are the examples in which inner classes can be defined
1. static inner class with a static method
Example:
class outer
{
static class inner
{
public static void add(intx,int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo1
{
public static void main(String args[])
{
outer.inner.add(15,10);
}
}
2. static inner class with non-static method
Example:
class outer
{
static class inner
{
public void add(intx,int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo2
{
public static void main(String args[])
{
outer.innerob = new outer.inner();
ob.add(12,13);
}
}
3. non-static inner class with a non-static method
Example:
class outer
{
class inner
{
public void add(intx,int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
}
class innerclass_demo3
{
public static void main(String args[])
{
outer ot = new outer();
outer.inner in = ot.new inner();
in.add(34,56);
}
}
4. non-static inner class with a static method
Note: it is an illegal combination. Only static variables are allowed and should be final.
Example:
class outer
{
class inner
{
/* Illegal combination */
/*public static void add(intx,int y)
{
int z = x + y;
System.out.println("add = " + z);
}*/
public static final int a = 45;
}
}
class innerclass_demo4
{
public static void main(String args[])
{
outer ot = new outer();
outer.inner in = ot.new inner();
System.out.println("Value of a = "+in.a);
}
}
5. Nested inner class in local method
Example:
class outer
{
public void display(intx,int y)
{
class inner
{
public void add(intx,int y)
{
int z = x + y;
System.out.println("add = " + z);
}
}
inner in = new inner();
in.add(x,y);
}
}
class innerclass_demo5
{
public static void main(String args[])
{
outer ob = new outer();
ob.display(23,56);
}
}