What is Inner Class in Java in Simple Mean – Advantages and Use

What is Inner Class In Java?

The Inner Classes In Java are those that are defined inside of other classes or interfaces that were primarily introduced.

Since Java is entirely object-oriented, inner classes help to make the language more realistic.

Use of Inner Class in Java?

A Java Inner Class or nested class is a class that is declared inside the class or interface.

We use inner classes to put classes and interfaces together in a way that makes them easier to read and maintain.

Also, it can access all the members of the outer class, including private data members and methods.

What are the Advantages of Java Inner classes?

The following listed below are 3 advantages of Java inner class.

  • Keeping code clean and easy to read.

  • Accessing the private methods of the outer class adds a new dimension and brings it closer to the real world.

  • Improving the code module.

Static Inner Class in Java

A Static Inner Class In Java is a class that is created inside another class. It can’t access data members and methods that aren’t static. It can be accessed by using the outer class name.

  • It can access both public and private static data members of the outer class.
  • The static nested class can’t access (instance) data members that are not static.

What is the difference between an inner class and an anonymous class in Java?

A local inner class is a class that is declared inside of a method.

An anonymous class, on the other hand, is declared when an instance is made.

So the anonymous class is made as the program runs.

How do Inner Classes Work in Java?

A Java inner class is defined inside the body of another class.

An inner class in Java can be declared private, public, protected, or with default access, but an outer class can only be public or have default access.

In Java, there are two kinds of classes that are nested inside other classes.

What is Meant By an Inner Class?

A class that is declared entirely inside the body of another class or interface is called an inner class or nested class.

It’s not the same as a subclass.

What is the Purpose Of Inner Class?

The purpose of Inner class In Java is a way for Java to keep things safe.

We know that the access modifier private can’t be attached to a class, but if the class is a member of another class, the inner class can be made private.

And this is also how you get to a class’s private members.

What are the 4 Types of Inner Classes in Java?

The following listed below are the 4 types of inner classes in Java.

  • Nested inner class
  • Method local inner classes
  • Static nested classes
  • Anonymous inner classes

Let’s talk about each of the above types in detail along with a clean Java program, which is important at every step because it gets harder as we go.

Nested Inner Class in Java

The Nested Inner Class In Java is part of the class that contains it.

Even if they are marked as private, non-static inner classes can access other members of the outer class.

Static nested classes can’t access other members of the class that contains them.

It can get to any private instance variable of the outer class.

Like any other instance variable, we can set the access modifier to private, protected, public, or default. Like a class, an interface can also be nested and can have access specifiers.

Example:

// program created by Glenn
// Java Program to Demonstrate Nested class
// Class 1
// Helper classes
class Outer {

	// Class 2
	// Simple nested inner class
	class Inner {

		// show() method of inner class
		public void show()
		{

			// Print statement
			System.out.println("Sample program In a nested class method");
		}
	}
}

// Class 2
// Main class
public class Main {

	// Main driver method
	public static void main(String[] args)
	{

		// Note how inner class object is created inside
		// main()
		Outer.Inner in = new Outer().new Inner();

		// Calling show() method over above object created
		in.show();
	}
}

Output:

Sample program In a nested class method

In order for you to test the Java code provided in this lesson, you must test the code in your code editor.

But if you wish to run this code online, we also have an online compiler in Java for you to test your Java code for free.

You can test the above example here! ➡Java Online Compiler 

Note : We can’t have a static method in a nested inner class because an inner class is implicitly connected to an object of its outer class, so it can’t define any static methods for itself. For example, the following program does not compile.

Example:

// program by Glenn
// Java Program to Demonstrate Nested class
// Where Error is thrown
// Class 1
// Outer class
class Outer {

	// Method defined inside outer class
void outerMethod()
	{

		// Print statement
		System.out.println("Sample inside outerMethod");
	}

	// Class 2
	// Inner class
 public class Inner {

		// Main driver method
		public static void main(String[] args)
		{

			// Display message for better readability
			System.out.println("Sample inside inner class Method");
		}
	}
}

Output:

Error: Could not find or load main class Inner
Caused by: java.lang.ClassNotFoundException: Inner

You can test the above example here! ➡Java Online Compiler 

Method Local Inner Class in Java

The Method Local Inner Class In Java can only be used inside the method where they are defined.

An inner class can be declared inside a method of an outer class, as shown in the example below, where Inner is an inner class inside outerMethod ().

Example:

// program created by Glenn
// Java Program to Illustrate Inner class can be
// declared within a method of outer class
// Class 1
// Outer class
class Outer {

	// Method inside outer class
	void outerMethod()
	{

		// Print statement
		System.out.println("sample inside outerMethod");

		// Class 2
		// Inner class
		// It is local to outerMethod()
		class Inner {

			// Method defined inside inner class
			void innerMethod()
			{

				// Print statement whenever inner class is
				// called
				System.out.println("sample inside innerMethod");
			}
		}

		// Creating object of inner class
		Inner y = new Inner();

		// Calling over method defined inside it
		y.innerMethod();
	}
}

// Class 3
// Main class
public class PIES {

	// Main driver method
	public static void main(String[] args)
	{

		// Creating object of outer class inside main()
		// method
		Outer x = new Outer();

		// Calling over the same method
		// as we did for inner class above
		x.outerMethod();
	}
}

Output:

sample inside outerMethod
sample inside innerMethod

You can test the above example here! ➡Java Online Compiler 

Method Local inner classes can’t use a local variable of the outer method until that local variable is declared as final.

For instance, the code below causes a compiler error.

Note : “x” is not final in outerMethod(), but it is tried to be accessed by innerMethod().

Example:

class Outer {
void outerMethod() {
	int x = 100;
	System.out.println("inside outerMethod");
	class Inner {
		void innerMethod() {
			System.out.println("x = "+x);
		}
	}
	Inner y = new Inner();
	y.innerMethod();
}
}
public class MethodLocalVariableDemo {
public static void main(String[] args) {
	Outer x=new Outer();
	x.outerMethod();
}
}

Output:

sample inside outerMethod
x = 100

You can test the above example here! ➡Java Online Compiler 

But the code below compiles and runs correctly (Note that x is final this time).

Example:

// program created by Glenn
class Outer {
void outerMethod() {
	final int x=100;
	System.out.println("sample inside outerMethod");
	class Inner {
		void innerMethod() {
			System.out.println("x = "+x);
		}
	}
	Inner y = new Inner();
	y.innerMethod();
}
}
public class MethodLocalVariableDemo {
	public static void main(String[] args){
	Outer x = new Outer();
	x.outerMethod();
	}
}

Output:

sample inside outerMethod
x = 100

You can test the above example here! ➡Java Online Compiler 

The main reason we need to declare a local variable as final is that it lives on the stack until the method is on the stack.

However, the object of the inner class might still live on the heap.

Methods in inner classes can’t be marked as private, protected, static, or transient.

However, they can be marked as abstract or final, but not both at the same time.

Static Nested Classes in Java

In Java, a static nested class is a class that is created inside of another class.

It can’t get to data members and methods that are not static.

You can get to it by using the outer class name. It can get to private static data members of the outer class.

In addition, static nested classes are not technically inner classes. They are like a static member of the outer class.

Example:

// program created by Glenn
// Java Program to Illustrate Static Nested Classes
// Importing required classes
import java.util.*;

// Class 1
// Outer class
class Outer {

	// Method
	private static void outerMethod()
	{

		// Print statement
		System.out.println("sample inside outerMethod");
	}

	// Class 2
	// Static inner class
	static class Inner {

		public static void display()
		{

			// Print statement
			System.out.println("sample inside inner class Method");

			// Calling method inside main() method
			outerMethod();
		}
	}
}

// Class 3
// Main class
public class PIES {

	// Main driver method
	public static void main(String args[])
	{

		Outer.Inner obj = new Outer.Inner();

		// Calling method via above instance created
		obj.display();
	}
}

Output:

sample inside inner class Method
sample inside outerMethod

You can test the above example here! ➡Java Online Compiler 

Anonymous Inner Classes in Java

The Anonymous Inner Class In Java is a nested class that doesn’t have a name.

A class with no name must be set up inside of another class.

So, this type of class is also called an anonymous inner class.

Anonymous inner classes are those that are declared without a name.

They are made in two different ways.

  • As a subclass of the type that was specified,
  • As an implementer of the given interface,

The syntax of an anonymous class expression is the same as calling a constructor, except that the class definition is in a block of code.

Syntax:

// sample created by Glenn
// Test can be interface,abstract/concrete class
Test t = new Test(){
// data members and methods
public void test_method(){
……..
……..
}
};

Example:

// Java Program to Illustrate Anonymous Inner classes
// Declaration Without any Name
// As a subclass of the specified type

// Importing required classes
import java.util.*;

// Class 1
// Helper class
class Demo {

	// Method of helper class
	void show()
	{
		// Print statement
		System.out.println(
			"i am Glenn I will show method of super class");
	}
}

// Class 2
// Main class
public class PIES {

	// An anonymous class with Demo as base class
	static Demo d = new Demo() {
		// Method 1
		// show() method
		void show()
		{
			// Calling method show() via super keyword
			// which refers to parent class
			super.show();

			// Print statement
			System.out.println("I'm a Writer and Computer programmer");
		}
	};

	// Method 2
	// Main driver method
	public static void main(String[] args)
	{
		// Calling show() method inside main() method
		d.show();
	}
}

Output:

i am Glenn I will show method of super class
I’m a Writer and Computer programmer

You can test the above example here! ➡Java Online Compiler 

Output Explanation

In the code above, we create an object of an inner class that isn’t named, but it implements the interface named Hello.

One interface alone may be implemented at a time by any anonymous inner class.

At any one time, it can either implement an interface or extend a class.

Summary

In summary, Inner Classes in Java are classes defined inside other classes or interfaces, contributing to the object-oriented nature of Java.

They enhance code organization, readability, and encapsulation, allowing access to private members of the outer class.

The four types of inner classes—Nested Inner Class, Method Local Inner Class, Static Nested Class, and Anonymous Inner Class—serve different purposes.

The examples provided demonstrate their usage and characteristics, emphasizing the importance of understanding their distinctions for effective Java programming.


Leave a Comment