Inner classes in Java

RMAG news

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

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

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

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

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

Please follow and like us:
Pin Share