TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Nested (Inner) Class Concept in Java
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Java OOPJava Tutorials

Nested (Inner) Class Concept in Java

Last updated: Aug 02, 2023 4:32 pm
By Meenakshi Agarwal
Share
9 Min Read
Java nested class or inner class with examples
Java nested class or inner class with examples
SHARE

In this tutorial, you will discover the insights about the concept of Java Nested Class, also known as Inner Class. There are follow up examples to get into the thick and thin of how can you create and use nested classes.

Contents
What is a nested class?Static Nested/Inner ClassNon-static Nested/Inner ClassMember level inner classAnonymous inner classLocal inner class

The major topics covered are:

1. What is Nested Class?
2. Static Nested Class
3. Non-static Nested Class

Let’s check out the detail of Java inner class and their types.

Java Nested Class Overview with Examples

Java nested class or inner class diagram

What is a nested class?

In Java, you can create a class inside another one. We term these type of constructs as a Nested Class. this concept help in combining the logic of multiple entities into one. Therefore, you get a higher level of encapsulation and code, which is more maintainable.

Below are some points to note:

  • A nested class has to honor the boundaries of its enclosing object.
  • It gets access to all public/private members of all classes appearing before it in the chain.
  • It implicitly becomes a part (member) of its ancestor in the chain.
  • You are free to mark it as private, public, protected, or package-private (default behavior), as needed.

Java has two distinctions in nested classes.

  • Static Inner Class, and
  • Non-static Inner Class

Let’s check out what are these in the subsequent section.

Static Nested/Inner Class

It is a nested class which we declare as static becomes the Static Nested Class. It behaves like a static member of the outer class.

Just like any other static member, this class also doesn’t have any control over instance variables and methods of the outer object. The programmer needs to specify the keyword static to make one such class.

The example below will help you visualize how a static nested class works:

public class Outer{
   public void method1() {
      System.out.println("This belongs to Outer Class");
   }

   static class Nested
   {
      public void method1() {
         System.out.println("This belongs to Static Nested Class");
      }
   }

   public static void main(String args[]) {
      Outer.Nested n = new Outer.Nested();	
      n.method1();
   }
}

The syntax to note about is how does the static nested class instantiate. After running the program, the output is:

This belongs to Static Nested Class

Non-static Nested/Inner Class

A non-static nested class happens to be the Inner Class.

The concept of inner classes is of great importance as it provides a security mechanism in Java. As such, we do not have any access to break into a Class once declared with the private access modifier. Therefore, we don’t mark any class as private.

We can achieve this functionality by declaring inner class private. Further, inner classes are of three types depending upon how you use them:

  • Member level Inner Class
  • Anonymous Inner Class
  • Local Inner Class

Member level inner class

Java allows us to write a class within a method. It got called as Member-level Inner Class. Note down the following points:

  • This class will only be local, and scope remains within the Method.
  • This type of inner class instantiates within the defined Method only.
  • You can’t create the instances of this class outside the block/method.

The example below shows one such class:

public class Outer {
   void method1() {

      class InnerClass {
         public void msg() {
            System.out.println("This is an inner class ");	
         }   
      }

      InnerClass ins = new InnerClass();
      ins.msg();
   }

   public static void main(String args[]) {
      Outer outer = new Outer();
      outer.method1();
   }
}

As you would expect, the output of the program after execution is:

This is an inner class

Anonymous inner class

The anonymous inner class is one that has a body with data and functions but does not have a name.

For an anonymous inner class, declaration and instantiation occur at the same time. A programmer may choose to use such a concept for overriding any method of a class or interface.

The example below shows its demo:

abstract class AnonClass {
   public abstract void method1();
}

public class Outer {

   public static void main(String args[]) {
      AnonClass ac = new AnonClass() 
      {
         public void method1() {
            System.out.println("This is an anonymous class");
         }
      };
      ac.method1();	
   }
}

The keyword Abstract makes sure the class is available w/o body. Similarly, for the method1, it makes sure the method is just a declaration. We’ll override it in the Main function.

After running the code, the output comes as:

This is an anonymous class

We can also use an anonymous class as an argument to a method. Simultaneously, we can utilize it to override the predefined function of the Inner Class.

The example below helps you visualize the above facts:

class Prev {
   void simplePrint() {
      System.out.println("hello");
   }
}

class Next {
   int x = 10;
   Prev prev = new Prev() {
      void simplePrint() {
         System.out.println("HELLO " + x);
      }
   };

   void print() {
      prev.simplePrint();
   }
}

public class Main {
   public static void main(String args[]) {
      Next next = new Next();
      Prev prev = new Prev();
      next.print();
      prev.simplePrint();
   }
}

This program overrides simplePrint function in Prev class. Whatever you define within the anonymous class remains in the scope of the instance of the inner class only (prev in this case).

We cannot create a new method within this instance as long as the same is not available in the Prev class initially. This case is similar to implementing an interface.

Please note that the anonymous class doesn’t permit a constructor declaration within.

After the execution, the output of the program is:

HELLO 10
hello

Local inner class

In Java, we can create a class inside a method which will have localized scope. Hence, it got called a Local Inner Class.

Its scope will be bound to the method. Also, we can instantiate it only in the body of its host.

Moreover, we can set it as private, unlike the usual way. If declared private, then we won’t be able to access it from outside.

The example below shows a local inner class:

class Outer {
   class Inner {
      public void meth() {
         System.out.println("Inner class");
      }
   }

   void print() {
      Inner inner = new Inner();
      inner.meth();
   }
}

public class Main {
   public static void main(String args[]) {

      Outer outer = new Outer();
      outer.print();
   }
}

After you run the program, the output comes as:

Inner class

Inner Classes are generally private by nature, unlike the case discussed above. Moreover, these inner classes can be useful in accessing Private Members of the outer class.

See the below example:

class Outer {
   private int num = 10;  
   public class Inner {
      public void print() {
         System.out.println("Private number access from inner class " + num); 
      }
   }
}

public class Test {

   public static void main(String args[]) {

      Outer out = new Outer();
      Outer.Inner in = out.new Inner();
      in.print();
   }
}

To execute the above code, you may have to save it as Test.java. Anyways, after running the program, it gets you the following output:

Private number access from inner class 10

We hope this tutorial on Java nested class (inner class) would have helped you figure out how it works in Java. Please do practice with the examples to get full clarity.

You Might Also Like

A Simple Guide to Exception Handling in Java

Difference Between Spring and Spring Boot

How to Use Java String Format with Examples

Java IRC Bot with Sample Code

Generate Random Number in Java – 10 Ways

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Java Abstract Class Overview with Examples Abstract Class Concept in Java
Next Article MySQL Declare Variable local, user-defined, system How to Declare Variables in MySQL

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x