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
}
}
Following are the examples in which inner classes can be defined
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);
}
}
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);
}
}
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);
}
}
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);
}
}
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);
}
}