DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Inner classes in Java

Member Inner Class
A class created within class and outside method.

//member inner class
class Outer{
    class Inner{
        int x = 3;
    }
    public static void main(String ar[]){
        Outer o = new Outer();
        Outer.Inner in = o.new Inner();
        System.out.println(in.x);
    }
}
//output : 3
Enter fullscreen mode Exit fullscreen mode

Anonymous Inner Class

A class created for implementing an interface or extending class. The java compiler decides its name.

//anonymous inner class
interface Anony{
    void printName();
}
class Main{

    public static void main(String ar[]){
        Anony a = new Anony(){
            public void printName(){
                System.out.println("Implementation of Annonymous inner class ");
            }
        };
        a.printName();
    }
}
//output : Implementation of Annonymous inner class 
Enter fullscreen mode Exit fullscreen mode

Local Inner Class
A class was created within the method.

//Local inner class

class Main{

    public static void main(String ar[]){
        Main m = new Main();
        m.display();
    }

    public void display(){

        class Local{
            public void name(){
                System.out.println("local");
            }
        }

        Local l = new Local();
        l.name();
    }

}
//output : local
Enter fullscreen mode Exit fullscreen mode

Static Nested Class
A static class was created within the class.

//static inner class
class Outer{
    static class Inner{
        static int x = 3;
    }
    public static void main(String ar[]){

        Outer.Inner in = new Outer.Inner();
        System.out.println(in.x);
    }
}
//output : 3
Enter fullscreen mode Exit fullscreen mode

Nested Interface

An interface created within class or interface.

//nested interface

class Outer{
    interface Nested{
        public void details();
    }
}
class Main implements Outer.Nested{
    @Override
    public void details(){
        System.out.println("Main class is implementing nested inner interface Nested present in Outer class");
    }
    public static void main(String a[]){
        Outer.Nested nested = new Main();
        nested.details();
    }
}
//output : Main class is implementing nested inner interface Nested present in Outer class
Enter fullscreen mode Exit fullscreen mode

Top comments (0)