Anonymous inner classes - Java

A class that has no name is known as anonymous inner class in java. It should be used if you have to override method of class or interface. Java Anonymous inner class can be created by two ways:

A) Class
B) Interface

1) Anonymous classes are just like local classes, besides they don’t have a name. In Java anonymous classes enables the developer to declare and instantiate a class at the same time.
2) In java normal classes are declaration, but anonymous classes are expressions so anonymous classes are created in expressions.
3) Like other inner classes, an anonymous class has access to the members of its enclosing class.

 

Program on Anonymous inner class

class abc
{
public void put()
{
System.out.println("this is abc class put methos");
}
}
public class anonymous1 {

            public static void main(String[] args) {

abc x=new abc(){
public void put()
{
System.out.println("Anonymous inner class put method");
}
};
x.put(); // calls anonymous put method. it will override the method
abc y=new abc();
y.put(); // calls abc class put method

}
}

Program on abstract classes and anonymous inner class

abstract class mysum
{
int a, b;
public void get(int x,int y)
{
a=x;
b=y;
}
abstract public void put();

}
public class anonymous1
{

            public static void main(String[] args)
{

mysum x=new mysum()   
{
public void put()  // implementation of abstract method.
{
System.out.println("Sum of 2nos "+(a+b));
}
};
x.get(43, 64);
x.put();


}

}

Note:
Normally abstract classes can’t be instantiated here new mysum() means anonymous inner class will be referenced, hence we can call get and put methods.

Program on Anonymous inner class using interfaces

interface abc
{
public void sum(int x,int y);

}
class xyz
{
abc c=new abc()    // anonymous inner class
{
public void sum(int x,int y)
{
System.out.println("Sumof 2nos"+(x+y));
}
};
public void sub(int x,int y)
{
System.out.println("Sub "+(x-y));
}
}

 

 
public class anony2
{

            public static void main(String[] args)
{
abc x=new abc()    // anonymous inner class
{
public void sum(int x,int y)
{
System.out.println("Sum of 2nos "+(x+y));
}
};
x.sum(5, 3);
xyz y=new xyz();
y.c.sum(54, 23);
y.sub(12, 2);
}       
}  

For
Online Classes

Contact Us: 9885348743