Inner Class

Author: Ravi Poswal

A class defined inside another class is referred to as an inner class. Inner class benefits:-

  • It is a method of logically joining classes, i.e., it is only utilised in one location.

  • Static class increases encapsulation

  • Inner class used for easily readable and maintenance 

 Inner classes are two types:-

  1. Static nested class

  2. Non-static nested class

1. STATIC NESTED CLASS/ STATIC CLASS

A static nested class uses the static keyword to define itself inside the scope of another class. It follows some rules:-

  • It lacks access to the outer class's instance members and methods.

  • It applies to every static member of its outer class.

 

Code Example

class A
{private static int a; 
static
{a=5;
System.out.println("outer class static block");
}
public static class B   //inner class start
{int b;
public B(int x)
{ b=x;
System.out.println("Inner Class constructor");
}
public void display()
{ 
System.out.println("a of outerclass is: "+ a);
System.out.println("b of inner class object is: "+ b);
}}
public static void main(String arg[])
{ 
A.B x=new A.B(10);
System.out.println("outer class");
x.display();
}
}

2. NON STATIC CLASS

A class is defined within another class without using a static keyword called inner class/non-static class.

  • It may be used as a static member of the outer class and a non-static member.

Code Example

class Out {    //outer class
static int x = 10; 
int y = 20; 
class Inner
{
  void display() 
{ 
 System.out.println("outer-x = " +x); 
System.out.println("outer-y = " +y); 
 } 
} 
public class Inner  //non-static inner class
{ public static void main(String[] args) 
{ 
Out Obj= new Out(); 
  Out.Inner inObj= Obj.new Inner();   
inObj.display(); 
} 
}
}

FAQs

An inner class in Java is a class defined inside another class. It helps in logically grouping classes and improving code organization. inner class is treating as member of the class

static class
non static class

A member inner class is a class defined inside another class but outside any method, and it can access all members of the outer class.

A static nested class uses the static keyword to define itself inside the scope of another class. It follows some rules:-
• It lacks access to the outer class's instance members and methods.
• It applies to every static member of its outer class.

An anonymous inner class is a class without a name, used for creating one-time objects, usually for interfaces or abstract classes.

Inner classes are used for better code organization, encapsulation, and when a class is closely related to another class.

Yes, an inner class can access all members (including private) of the outer class.

Yes, inner classes can have constructors just like normal classes.