Programming





Inner Class in Java

Inner Class in Java


by Administrator | 04-Apr-2020
Java

Tags:  Nested Class  Inner Class  Static Inner Class  Method Local Inner Class  Anonymous Inner Class

Share: 


Defining a class inside the scope of another class or interface is known as an inner class. It is also called as Nested Class. An inner class can access all the members of the outer class, even private members.

 Types of Inner Classes

  1. Plain Inner class
  2. Static inner class
  3. Method local inner class
  4. Anonymous inner class

1. Plain Inner class

Defining one class inside another class without a static modifier is known as an inner class. From the inner class, any member of the outer class can be accessed.  

Syntax

class Outer {
    class Inner {
        statements;
    }
    statements;
}

 Every class will generate a separate class file when compiled. 

2. Static inner class

An inner class declared with a static modifier inside another class is known as a static inner class. A static inner class can have static members. 

Program

public class StaticInnerClass {
    static class InnerClass {
        void justSayingHey() {
            System.out.println("Hey!!!");
        }
    }
    public static void main(String[] args) {
        StaticInnerClass.InnerClass sic = new StaticInnerClass.InnerClass();
        sic.justSayingHey();
    }
}

Output

Hey!!! 

3. Method Local Inner Class

When a class is defined inside a method of the outer class it is called Method Local Inner Class. The scope of local inner class is restricted within the method.

 Program

public class OuterClass {
    void doStuff() {
        int size = 10;
        class InnerClass {
            public void print() {
                System.out.println("This size is: " + size);
            }
        }
        InnerClass inner = new InnerClass();
        inner.print();
    } 
    public static void main(String args[]) {
        OuterClass outer = new OuterClass();
        outer.doStuff();
    }
}

Output

This size is: 10

4. Anonymous Inner Class

Anonymous Classes are created dynamically without any name. An anonymous inner class cannot be a top level class. It will always be defined inside an inner class.

The object for Anonymous Class will be created on the fly where the class is defined. Anonymous Class cannot be instantiated more than once.

Program

abstract class Animal {
    abstract void eat();
}
public class AnonymousInnerClass {
    public static void main(String args[]) {
        Animal animal = new Animal() {
            void eat() {
                System.out.println("Animals eating like animals.");
            }
        };
        animal.eat();
    }
}

Output

Animals eating like animals.

Comments:


There are no comments.

Enter a new Comment:










Copyright Šprgrmmng. All rights reserved.