Skip to main content

Inner Class in Java

Inner class in Java

In this article, we are going to learn a special type of class which is known as the Inner class in Java. Let's start this tutorial with the definition of the inner class, then we'll look at the types of the inner class, and how to create and use them.

What is Inner class in Java?

An inner class is a class that is defined within another class. An inner class can be considered as a member of the outer class and like the other members, it can have any access specifier and can be declared as abstract or final.
There are generally two types of inner class in java:
  • Static inner class or Static class
  • Non-Static Inner class
Whenever the inner class is marked with the static keyword, it will be called a Static class in java. Otherwise non-static inner class.
In this tutorial, we are going to discuss the non-static inner class in java, so whenever we refer to the inner class it means we are talking about the non-static inner class.
If you want to learn the static class in java, read this article: https://www.java8net.com/2020/11/static-class-in-java.html

How to create an Inner class in Java?

We can define a non-static inner class in 3 different ways:
  • Class-level inner class
  • Method-level inner class
  • Anonymous inner class

Class-level Inner class in Java

When a class is declared just within the block of the outer class, it is known as a class-level inner class. Let's first look at the below code snippet to have a basic idea of the class-level inner class.
class OuterClass{
	/*
	 *  Body of the Outer class
	 */
	class InnerClass {
		/*
		 * Body of the Inner class
		 */
	}
}
Above, we take a look at how to define an inner class in java.
Now, it's time to do some useful examples to get a better understanding of the inner classes. An inner class, defined within the outer class, has access to all the members of the outer class even private members as well. Below, we will create a Product class that contains an inner class to apply taxation. Let see how to create this Product-Taxation class relationship and how to use it.

Java Inner Class Example 1: Create a Product-Taxation relationship

class Product {
	private String name;
	private double price;
	private Taxation taxation;
	private double priceAfterTax;

	Product(String name, double p, double r) {
		this.name = name;
		this.price = p;
		this.taxation = new Taxation(r);
		taxation.applyTax();
	}

	class Taxation {
		private double rate;
        
		Taxation(double r) {
			this.rate = r;
		}
        
		void applyTax() {
			priceAfterTax = price * (1 + rate);
		}
	}

	void setTaxRate(double taxRate) {
		this.taxation = new Taxation(taxRate);
		taxation.applyTax();
	}
    
	@Override
	public String toString() {
		return name + " : " + price + "(@" + taxation.rate + ")" + " = "
				+ priceAfterTax;
	}
}
Above, we have created a Product class and to create an object, we need to provide the name, price, and applicable tax rate into the constructor. In the constructor, we have created an object of the Taxation class, Taxation is an inner class of Product, and then invoked the applyTax() method from the constructor.
Taxation inner class demands a double value as tax rate and it has an applyTax() method which applies the tax rate onto the price of the product. If you have noticed that the applyTax() method accessing a private member of the Product class which is a benefit of making an inner class.
In the Product class, we have overridden the toString() method just to format the details of a product. Also, we have setTaxRate() method in the Product class to update the tax rate of the Product.
Let's look at the below code to see how to create an object of the Product and use it.
class ProductDemo {
	public static void main(String[] args) {
		Product laptop = new Product("Laptop", 45000, 0.18);
		System.out.println(laptop);
		laptop.setTaxRate(0.28);
		System.out.println(laptop);
	}
}
Output
Laptop : 45000.0(@0.18) = 53100.0
Laptop : 45000.0(@0.28) = 57600.0

Method-level Inner class in Java

A Method-level inner class is a class that is defined inside the block of the method. Similar to the class-level inner class, an inner class defined inside the method has also access to all the members of the outer class.
Below is the code snippet for defining a method-level inner class in java.
class OuterClass{
	/*
	 * Body of the Outer class
	 */
	void anyMethod() {
		/*
		 * Method which contains the Inner class
		 */
		class InnerClass {
			/*
			 * Body of the Inner Class
			 */
		}
	}
}
Note :
  1. An inner class defined inside the method is local to the method. The method-level inner class is not accessible outside the method, not even in the outer class.
  2. An inner class defined inside the method can access the final local variables declared within the method. Java 8 onwards, it can access effectively final local variables too.
After having a glance at the method level inner class in java, let's do some functional examples to get a better understanding of it.

Java Inner Class Example 2: Create SessionCalculator which uses method level inner class.

class SessionCalculator {

	static double calculateCallingBill(long durationInSeconds,
			double callRatePerMinute) {
		class CallSession {
			public double calculate() {
				return durationInSeconds / 60 * callRatePerMinute;
			}
		}
		return new CallSession().calculate();
	}

	static double calculateDataBill(long dataUsedInBytes,
			double dataRatePerMB) {
		class DataSession {
			public double calculate() {
				return dataUsedInBytes / 1000000 * dataRatePerMB;
			}
		}
		return new DataSession().calculate();
	}
}
Above, we have created a SessionCalculator to calculate call/data bill, one method for each. Each method contains an inner class to generate bills. Both the methods are using the method's local variable (as these variables are effectively final). Let see how to use this class.
class SessionCalculatorDemo {

	public static void main(String[] args) {
		/*
		 * Generate bill for 240 sec @1.2 Rupees/Min
		 */
		System.out.println("Generate bill for 240 sec @1.2 Rupees/Min");
		double callingBill = SessionCalculator.calculateCallingBill(240, 1.2);
		System.out.println("Calling bill : " + callingBill);
		
		/** For new line */
		System.out.println();

		/*
		 * Generate bill for 2000 KB @1.5 Rupees/MB
		 */
		System.out.println("Generate bill for 2000 KB @1.5 Rupees/MB");
		double dataBill = SessionCalculator.calculateDataBill(2000, 1.5);
		System.out.println("Data bill : " + dataBill);
	}
}
Output
Generate bill for 240 sec @1.2 Rupees/Min
Calling bill : 4.8

Generate bill for 2000 KB @1.5 Rupees/MB
Data bill : 3.0

Anonymous Inner Class

We have one another way to define an inner class in java through the Anonymous Inner class.
  • It is a local inner class without the name.
  • An anonymous class can only be defined as an implementation of an interface or a subclass of an abstract class.
  • It can be defined either inside the class or the method.
Let's first look at the Syntax to define Anonymous inner class in java.
/*
* Let say, A is an interface or abstract class
*/
A obj = new A() {
  /*
   * Body of A 
   */
};
Note: We cannot declare any constructor in the Anonymous inner class

Java Inner Class Example 3: Create and use employee salary calculator using anonymous inner class in java.

interface Calculator {
	int calculate();
}

class Employee {
	private int salary;
	private int fine;
	private int reimbursement;

	Employee(int salary, int fine, int reimbursement) {
		this.salary = salary;
		this.fine = fine;
		this.reimbursement = reimbursement;
	}

	int calculateTotalSalary() {
		Calculator totalSalaryCalculator = new Calculator() {
			@Override
			public int calculate() {
				return salary + reimbursement - fine;
			}
		};
		return totalSalaryCalculator.calculate();
	}
}
In the above example, we have created an Employee class which has the method which calculates the total salary of the employee. The calculateTotalSalary() internally uses anonymous inner class. Let's create an object of employee and calculate the total salary.
class EmployeeSalaryCalculatorDemo {
	public static void main(String[] args) {
		Employee employee = new Employee(25000, 1500, 1000);
		System.out.println("Total Salary : " + employee.calculateTotalSalary());
	}
}
Output
Total Salary : 24500

Conclusion

In this article, we have studied what is an inner class in java and how to create different types of inner class.
Thanks for reading this article.
If, we missed something please let us know in the comment section below.
Happy Learning

Related Articles

Static Class in Java
Immutable Class in Java

Comments