Java Inner Classes

Last updated on Dec 25 2022
Prabhas Ramanathan

Java inner class or nested class is a class which is declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.

Table of Contents

Syntax of Inner class

1. class Java_Outer_class{ 
2. //code 
3. class Java_Inner_class{ 
4. //code 
5. } 
6. }

Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

Do You Know

• What is the internal code generated by the compiler for member inner class ?
• What are the two ways to create annonymous inner class ?
• Can we access the non-final local variable inside the local inner class ?
• How to access the static nested class ?
• Can we define an interface within the class ?
• Can we define a class within the interface ?

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
• Non-static nested class (inner class)
1. Member inner class
2. Anonymous inner class
3. Local inner class
• Static nested class

Member Inner Class A class created within class and outside method.
Anonymous Inner Class A class created for implementing interface or extending class. Its name is decided by the java compiler.
Local Inner Class A class created within method.
Static Nested Class A static class created within class.
Nested Interface An interface created within class or interface.

 

Java Member inner class

A non-static class that is created inside a class but outside a method is called member inner class.
Syntax:

1. class Outer{ 
2. //code 
3. class Inner{ 
4. //code 
5. } 
6. }

Java Member inner class example

In this example, we are creating msg() method in member inner class that is accessing the private data member of outer class.

1. class TestMemberOuter1{ 
2. private int data=30; 
3. class Inner{ 
4. void msg(){System.out.println("data is "+data);} 
5. } 
6. public static void main(String args[]){ 
7. TestMemberOuter1 obj=new TestMemberOuter1(); 
8. TestMemberOuter1.Inner in=obj.new Inner(); 
9. in.msg(); 
10. } 
11. }

 

Output:
data is 30

Internal working of Java member inner class

The java compiler creates two class files in case of inner class. The class file name of inner class is “Outer$Inner”. If you want to instantiate inner class, you must have to create the instance of outer class. In such case, instance of inner class is created inside the instance of outer class.

Internal code generated by the compiler

The java compiler creates a class file named Outer$Inner in this case. The Member inner class have the reference of Outer class that is why it can access all the data members of Outer class including private.

1. import java.io.PrintStream; 
2. class Outer$Inner 
3. { 
4. final Outer this$0; 
5. Outer$Inner() 
6. { super(); 
7. this$0 = Outer.this; 
8. } 
9. void msg() 
10. { 
11. System.out.println((new StringBuilder()).append("data is ") 
12. .append(Outer.access$000(Outer.this)).toString()); 
13. } 
14. }

Java Anonymous inner class

A class that have no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:
1. Class (may be abstract or concrete).
2. Interface

Java anonymous inner class example using class

1. abstract class Person{ 
2. abstract void eat(); 
3. } 
4. class TestAnonymousInner{ 
5. public static void main(String args[]){ 
6. Person p=new Person(){ 
7. void eat(){System.out.println("nice fruits");} 
8. }; 
9. p.eat(); 
10. } 
11. }

 

Output:
nice fruits

Internal working of given code

1. Person p=new Person(){ 
2. void eat(){System.out.println("nice fruits");} 
3. };

1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

1. import java.io.PrintStream; 
2. static class TestAnonymousInner$1 extends Person 
3. { 
4. TestAnonymousInner$1(){} 
5. void eat() 
6. { 
7. System.out.println("nice fruits"); 
8. } 
9. }

Java anonymous inner class example using interface

1. interface Eatable{ 
2. void eat(); 
3. } 
4. class TestAnnonymousInner1{ 
5. public static void main(String args[]){ 
6. Eatable e=new Eatable(){ 
7. public void eat(){System.out.println("nice fruits");} 
8. }; 
9. e.eat(); 
10. } 
11. }

 

Output:
nice fruits

Internal working of given code

It performs two main tasks behind this code:

1. Eatable p=new Eatable(){ 
2. void eat(){System.out.println("nice fruits");} 
3. };

1. A class is created but its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Eatable type.

Internal class generated by the compiler

1. import java.io.PrintStream; 
2. static class TestAnonymousInner1$1 implements Eatable 
3. { 
4. TestAnonymousInner1$1(){} 
5. void eat(){System.out.println("nice fruits");} 
6. }

Java Local inner class

A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.

Java local inner class example

1. public class localInner1{ 
2. private int data=30;//instance variable 
3. void display(){ 
4. class Local{ 
5. void msg(){System.out.println(data);} 
6. } 
7. Local l=new Local(); 
8. l.msg(); 
9. } 
10. public static void main(String args[]){ 
11. localInner1 obj=new localInner1(); 
12. obj.display(); 
13. } 
14. }

 

Output:
30

Internal class generated by the compiler

In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

1. import java.io.PrintStream; 
2. class localInner1$Local 
3. { 
4. final localInner1 this$0; 
5. localInner1$Local() 
6. { 
7. super(); 
8. this$0 = Simple.this; 
9. } 
10. void msg() 
11. { 
12. System.out.println(localInner1.access$000(localInner1.this)); 
13. } 
14. }

Rule: Local variable can’t be private, public or protected.

Rules for Java Local Inner class

1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.

Example of local inner class with local variable

1. class localInner2{ 
2. private int data=30;//instance variable 
3. void display(){ 
4. int value=50;//local variable must be final till jdk 1.7 only 
5. class Local{ 
6. void msg(){System.out.println(value);} 
7. } 
8. Local l=new Local(); 
9. l.msg(); 
10. } 
11. public static void main(String args[]){ 
12. localInner2 obj=new localInner2(); 
13. obj.display(); 
14. } 
15. }

 

Output:
50

Java Local inner class

A class i.e. created inside a method is called local inner class in java. If you want to invoke the methods of local inner class, you must instantiate this class inside the method.

Java local inner class example

1. public class localInner1{ 
2. private int data=30;//instance variable 
3. void display(){ 
4. class Local{ 
5. void msg(){System.out.println(data);} 
6. } 
7. Local l=new Local(); 
8. l.msg(); 
9. } 
10. public static void main(String args[]){ 
11. localInner1 obj=new localInner1(); 
12. obj.display(); 
13. } 
14. }

 

Output:
30

Internal class generated by the compiler

In such case, compiler creates a class named Simple$1Local that have the reference of the outer class.

1. import java.io.PrintStream; 
2. class localInner1$Local 
3. { 
4. final localInner1 this$0; 
5. localInner1$Local() 
6. { 
7. super(); 
8. this$0 = Simple.this; 
9. } 
10. void msg() 
11. { 
12. System.out.println(localInner1.access$000(localInner1.this)); 
13. } 
14. }

Rule: Local variable can’t be private, public or protected.

Rules for Java Local Inner class

1) Local inner class cannot be invoked from outside the method.
2) Local inner class cannot access non-final local variable till JDK 1.7. Since JDK 1.8, it is possible to access the non-final local variable in local inner class.

Example of local inner class with local variable

1. class localInner2{ 
2. private int data=30;//instance variable 
3. void display(){ 
4. int value=50;//local variable must be final till jdk 1.7 only 
5. class Local{ 
6. void msg(){System.out.println(value);} 
7. } 
8. Local l=new Local(); 
9. l.msg(); 
10. } 
11. public static void main(String args[]){ 
12. localInner2 obj=new localInner2(); 
13. obj.display(); 
14. } 
15. }

 

Output:
50

So, this brings us to the end of blog. This Tecklearn ‘Java Inner Classes’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Java Inner Classes"

Leave a Message

Your email address will not be published. Required fields are marked *