This post is an extended post of Core Java tutorial series, where we are going to discuss Nested Class and inner class in Java with the help of examples.
In Java, it’s possible to define a class inside another class. Such classes are called Nested classes. We can use the access modifiers like private, public, protected, or default for an inner class, and the outer class can have only default or public access modifiers.
Types of Nested Class
Java Nested class are divided into two types:
- Static Nested Class
- Non-Static Nested Class
Static Nested Class
In Java, if we Can define the inner class as static, so such kind of classes is called a static nested class. But those classes are not called a static inner class.
As the nested class is defined with the static keyword, that’s why the nested class nature is static, so this type of nested class doesn’t share any relationship with the instance outer class. A static nested class can able to access the static members of the outer class.
Static nested classes are also the same as any top-level classes so that you can create a static class object with the following statement:
OuterClass.InnerClass obj = new OuterClass.InnerClass();
Let us see an example for better understand:
Public class MotherBoard { String model; public MotherBoard(String model) { this.model = model; } static class USB { int usb2 = 2; int usb3 = 1; int getTotalPorts() { return usb2 + usb3; } } } public class Main { public static void main(String[] args) { MotherBoard.USB usb = new MotherBoard.USB(); System.out.println("Total Ports = " + usb.getTotalPorts()); } }
Let us see another example where we try to access a non-static variable inside a static class:
// Java program to demonstrate accessing // a static nested class // outer class class OuterClass { // static member static int outer_x = 10; // instance(non-static) member int outer_y = 20; // private member private static int outer_private = 30; // static nested class static class StaticNestedClass { void display() { // can access static member of outer class System.out.println("outer_x = " + outer_x); // can access display private static member of outer class System.out.println("outer_private = " + outer_private); // The following statement will give compilation error // as static nested class cannot directly access non-static membera // System.out.println("outer_y = " + outer_y); } } } // Driver class public class StaticNestedClassDemo { public static void main(String[] args) { // accessing a static nested class OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass(); nestedObject.display(); } }
Important points to Remember
- Using the nested class concept, we can make the code more readable and better encapsulation.
- In the Java programming language, the outer class treats the inner class as a regular member of the class. The inner classes are treated like methods and variables like an outer class.
- As the inner classes are treated as a member of the outer class, you can apply the access modifiers like private, protected to the inner class, which is not possible to assign the access modifiers like private and protected in a normal class.
- As the nested classes are treated like members by the outer class, so you can use dot(.) operator to access the nested class and its members.
Non-Static Nested Class
A non-static nested class is indirectly known as an inner class in Java. The Java inner class is associated with the object of the outer class. That’s why the inner class is treated like other variables and methods of the outer class.
As the inner class is associated with the outer class object or instance, so we can’t declare static variables inside the inner class.
class MyOuterClassDemo { private int x= 1; public void innerInstance() { MyInnerClassDemo inner = new MyInnerClassDemo(); inner. seeOuter(); } public static void main(String args[]) { MyOuterClassDemo obj = new MyOuterClassDemo(); obj.innerInstance(); } // inner class definition class MyInnerClassDemo { public void seeOuter () { System.out.println("Outer Value of x is :" + x); } } // close inner class definition } // close Top level class definition
Accessing Members of Outer Class within Inner Class
Like as we discussed, we can access the members of the outer class from an inner class using this keyword. As we have mentioned above, the object of java’s inner class is a part of the outer class object, So for creating an instance of inner class firstly, we need to create an instance of the outer class.
You can instantiate the inner class like below:
OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Let us see an example to understand very easily:
public class Car { String carName; String carType; public Car(String name, String type) { this.carName = name; this.carType = type; } private String getCarName() { return this.carName; } class Engine { String engineType; void setEngine() { // Accessing carType property of Car if(Car.this.carType.equals("4WD")) { // Invoking method getCarName() of Car if(Car.this.getCarName().equals("Crysler")) { this.engineType = "Bigger"; } else { this.engineType = "Smaller"; } }else{ this.engineType = "Bigger"; } } String getEngineType() { return this.engineType; } } } public class CarMain { public static void main(String[] args) { Car car1 = new Car("Mazda", "8WD"); Car.Engine engine = car1.new Engine(); engine.setEngine(); System.out.println("Engine Type for 8WD= " + engine.getEngineType()); Car car2 = new Car("Crysler", "4WD"); Car.Engine c2engine = car2.new Engine(); c2engine.setEngine(); System.out.println("Engine Type for 4WD = " + c2engine.getEngineType()); } }
There are another two special kinds of inner classes is present that are:
- Local inner classes
- Anonymous Inner classes
Local Inner Classes
If a class is defined inside a method body is called a local inner class. Since the local class is not associated with the object of the outer class, they belong to the block where they are defined within. That’s why we can’t use the access modifiers like public, private, and protected for inner class. The only allowed modifiers are abstract and final.
The inner class can access the fields of the outer class, but the local class must be instantiated in the block where they are defined.
Rules Of Inner Class
- The scope of the inner class is restricted within the block where they are defined.
- You can not instantiate the local inner class outside the block where it is defined.
- A local class can have access to the members of its local inner class.
- An abstract class can extend local inner classes or implement an interface.
How to Declare a local Inner Class
We can declare a local inner class within a block, and that may be a method’s body, for loop or an if statement.
What Happens when you compile
When a program is compiled, which has a local inner class, then that time, two .class files will be generated one is for the outer class, and one is for the inner class, but the inner class has the reference to the outer class.
// Java program to illustrate Declaration of // local inner classes inside an if statement public class Outer { public int data = 10; public int getData() { return data; } public static void main(String[] args) { Outer outer = new Outer(); if(outer.getData() < 20) { // Local inner class inside if clause class Inner { public int getValue() { System.out.println("Inside Inner class"); return outer.data; } } Inner inner = new Inner(); System.out.println(inner.getValue()); } else { System.out.println("Inside Outer class"); } } }
Anonymous Inner Class
A Local class without a name is called an anonymous inner class and for which only one object is created. An Anonymous class is defined and instantiated in a single statement.
Anonymous inner class can be created in two ways
- By extending an abstract class or concrete class
- By Implementing interface
As we mentioned above that the anonymous class doesn’t have any name, so it’s not possible to define any constructor for that. Generally, the anonymous class is used when we need to override the method or interface of a class.
Syntax Of Anonymous Class
Here Demo may be an interface, class (abstract/concrete)
Demo t = new Demo() { // data members and methods public void demo_method() { ........ ........ } }
Let us see a simple program with the class to understand how to use in real-time
abstract class AnonymousInner { public abstract void mymethod(); } public class Outer_class { public static void main(String args[]) { AnonymousInner inner = new AnonymousInner() { public void mymethod() { System.out.println("This is an example of anonymous inner class"); } } inner.mymethod(); } }
We can also create an anonymous class with an interface, let check it out
//Java program to demonstrate need for Anonymous Inner class interface Age { int x = 21; void getAge(); } class AnonymousDemo { public static void main(String[] args) { // Myclass is implementation class of Age interface MyClass obj=new MyClass(); // calling getage() method implemented at Myclass obj.getAge(); } } // Myclass implement the methods of Age Interface class MyClass implements Age { @Override public void getAge() { // printing the age System.out.print("Age is "+x); } }
we see in the above program that we have created a separate class and implement that interface in a class after that from main methods we are calling the method but the same thing we can do that by an anonymous class, check the below program
//Java program to demonstrate Anonymous inner class interface Age { int x = 21; void getAge(); } class AnonymousDemo { public static void main(String[] args) { // Myclass is hidden inner class of Age interface // whose name is not written but an object to it // is created. Age oj1 = new Age() { @Override public void getAge() { // printing age System.out.print("Age is "+x); } }; oj1.getAge(); } }
I hope the above tutorial helps to understand the importance and use of Java inner class, if you have found any mistake or you want to give us any suggestion for more improvement, then you can write in the comment section.
Ref: article
Leave a Reply