BeginnersBook

  • Home
  • Java
    • Java OOPs
    • Java Collections
    • Java Examples
  • C
    • C Examples
  • C++
    • C++ Examples
  • DBMS
  • Computer Network
  • Python
    • Python Examples
  • More…
    • jQuery
    • Kotlin
    • WordPress
    • SEO
    • JSON
    • JSP
    • JSTL
    • Servlet
    • MongoDB
    • XML
    • Perl

Inner classes in java: Anonymous inner and static nested class

Last Updated: October 25, 2022 by Chaitanya Singh | Filed Under: java

What is an inner class?

Inner class are defined inside the body of another class (known as outer class). These classes can have access modifier or even can be marked as abstract and final. Inner classes have special relationship with outer class instances. This relationship allows them to have access to outer class members including private members too.

Inner classes can be defined in four different following ways as mentioned below:

1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class

1) Inner class

An inner class is declared inside the curly braces of another enclosing class. Inner class is coded inside a Top level class as shown below:-

//Top level class definition
class MyOuterClassDemo {
   private int myVar= 1;

   // inner class definition
   class MyInnerClassDemo {
      public void seeOuter () {
         System.out.println("Value of myVar is :" + myVar);
      }
    } // close inner class definition
} // close Top level class definition

Inner class acts as a member of the enclosing class and can have any access modifiers: abstract, final, public, protected, private, static.
Inner class can access all members of the outer class including those marked private as shown in the above example where inner class is accessing the private variable "myVar" of outer class.

Instantiating an inner class
To instantiate an instance of inner class, there should be a live instance of outer class. An inner class instance can be created only from an outer class instance. An inner class shares a special relationship with an instance of the enclosing class.
Instantiating an inner class from within code in outer 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

Output:

Outer Value of x is :1

Instantiating an inner class from outside the outer class Instance Code:
The public static void main code in the above example can be replaced with this one. It will also give the same output.

public static void main(String args[]){
   MyOuterClassDemo.MyInnerClassDemo inner = new MyOuterClassDemo().new MyInnerClassDemo();
   inner. seeOuter();
}

2) Method–Local inner classes

A method local inner class is defined within a method of the enclosing class. If you want to use inner class , you must instantiate the inner class in the same method, but after the class definition code. Only two modifiers are allowed for method-local inner class which are abstract and final.The inner class can use the local variables of the method (in which it is present), only if they are marked final.

//Top level class definition
class MyOuterClassDemo {
   private int x= 1;

   public void doThings(){
      String name ="local variable";
      // inner class defined inside a method of outer class
      class MyInnerClassDemo {
        public void seeOuter () {
           System.out.println("Outer Value of x is :" + x);
           System.out.println("Value of name is :" + name);//compilation error!!
        } //close inner class method
      } // close inner class definition
   } //close Top level class method
} // close Top level class

The above code will throw a compilation error as Inner class cannot use the non-final variables of the method, in which it is defined.
This is how it can be fixed: If we mark the variable as final then inner class can use it.

final String name ="local variable";// inner object can use it

3) Anonymous Inner Classes

It is a type of inner class which

  1. has no name
  2. can be instantiated only once
  3. is usually declared inside a method or a code block ,a curly braces ending with semicolon.
  4. is accessible only at the point where it is defined.
  5. does not have a constructor simply because it does not have a name
  6. cannot be static

Example:

package beginnersbook.com;
class Pizza{
   public void eat()
   {
      System.out.println("pizza");
   }
}
class Food {
   /* There is no semicolon(;)  
    * semicolon is present at the curly braces of the method end.
    */
   Pizza p = new Pizza(){
      public void eat()
      {
         System.out.println("anonymous pizza");
      }
   };
}

4) Static Nested Classes

A static nested classes are the inner classes marked with static modifier.Because this is static in nature so this type of inner class doesn’t share any special kind of relationship with an instance of outer class.A static nested class cannot access non static members of outer class.

Example:

class Outer{
   static class Nested{}
}

A static nested class can be instantiated like this:

class Outer{// outer class
   static class Nested{}// static nested class
}

class Demo{
   public static void main(string[] args){
      // use both class names
      Outer.Nested n= new Outer.Nested();
   }
}

Reference(s)
Java 2 by Kathy Sierra and Bert Bates

❮ PreviousNext ❯

Top Related Articles:

  1. Java – parameterized constructor with example
  2. Java Date Format examples
  3. How to Parse Date in Desired format – Java Date
  4. Static and dynamic binding in java
  5. Constructor Overloading in Java with examples

Tags: Java-OOPs

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

– Chaitanya

Comments

  1. surya says

    May 27, 2014 at 6:26 PM

    Nice examples and clear understanding.Thanks

    Reply
  2. junaid ahmad says

    October 26, 2014 at 6:29 PM

    i really like this website.
    because all stuff has described very clear.

    Reply
  3. kurmathireddy k says

    June 24, 2015 at 10:03 AM

    in first example we can’t access abstract modifiers in that example we will get error

    Reply
  4. sam says

    May 31, 2016 at 3:15 AM

    nice tutorial bro

    Reply
  5. Anand says

    December 19, 2016 at 1:43 PM

    Nice keep it up…!
    Example are very clear to understand, it help me to understand basic concept of java very clearly…

    Reply

Leave a Reply Cancel reply

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

Java Tutorial

Java Introduction

  • Java Index
  • Java Introduction
  • History of Java
  • Features of Java
  • C++ vs Java
  • JDK vs JRE vs JVM
  • JVM - Java Virtual Machine
  • First Java Program
  • Variables
  • Data Types
  • Operators

Java Flow Control

  • Java If-else
  • Java Switch-Case
  • Java For loop
  • Java while loop
  • Java do-while loop
  • Continue statement
  • break statement

Java Arrays

  • Java Arrays

OOPs Concepts

  • OOPs Concepts
  • Constructor
  • Java String
  • Static keyword
  • Inheritance
  • Types of inheritance
  • Aggregation
  • Association
  • Super Keyword
  • Method overloading
  • Method overriding
  • Overloading vs Overriding
  • Polymorphism
  • Types of polymorphism
  • Static and dynamic binding
  • Abstract class and methods
  • Interface
  • Abstract class vs interface
  • Encapsulation
  • Packages
  • Access modifiers
  • Garbage Collection
  • Inner classes
  • Static import
  • Static constructor

Java Exception Handling

  • Exception handling
  • Java try-catch
  • Java throw
  • Java throws
  • Checked and Unchecked Exceptions
  • Jav try catch finally
  • Exception Examples
  • Exception Propagation

Collections Framework

  • Collections in Java
  • Java ArrayList
  • Java LinkedList
  • Java Vector
  • Java HashSet
  • Java LinkedHashSet
  • Java TreeSet
  • Java HashMap
  • Java TreeMap
  • Java LinkedHashMap
  • Java Queue
  • Java PriorityQueue
  • Java Deque
  • Comparable interface
  • Comparator interface
  • Collections Interview Questions

MORE ...

  • Java Scanner Class
  • Java 8 Features
  • Java 9 Features
  • Java Conversion
  • Java Date
  • Java Multithreading
  • Java I/O
  • Java Serialization
  • Java Regex
  • Java AWT
  • Java Swing
  • Java Enum
  • Java Annotations
  • Java main method
  • Java Interview Q

Copyright © 2012 – 2025 BeginnersBook . Privacy Policy . Sitemap