An anonymous class is a temporary Class & Object, it is mandatory that an anonymous class must have its parent, we always keep its reference to its parent.
Lets define an anonymous class in 3 different ways:
1st Way: (create a file AnonymousDemoImpl.java inside com.dev21century):
package com.dev21century;
interface AnonymousDemo
{
public void show();
}
public class AnonymousDemoImpl {
int x = 100;
static int y = 200;
AnonymousDemo display(){
return (new AnonymousDemo(){
public void show()
{
System.out.println("x = " + x);
System.out.println("y = " + y);
}});
}
public static void main(String[] args) {
AnonymousDemoImpl anonymous = new AnonymousDemoImpl();
AnonymousDemo anonymousInterface = anonymous.display();
anonymousInterface.show();
}
}
Output:
In above program we have created an anonymous class inside display method, and there is no way to get object of that class in main() method. That’s why we have created an interface (AnonymousDemo), and made our anonymous class as a child of that interface. In main() method we have called the display method which returns object of anonymous class in a reference variable of interface.
Here compiler creates separate .class files for all anonymous classes and name them like Outer$1.class, Outer$2.class etc. In our program the .class file name is AnonymousDemoImpl$1.class.
2nd Way to create anonymous class:
Alter above program as follows:
package com.dev21century;
interface AnonymousDemo
{
public void show();
}
public class AnonymousDemoImpl {
int x = 10;
static int y = 20;
void display(AnonymousDemo annoInterface)
{
annoInterface.show();
}
public static void main(String[] args)
{
{
AnonymousDemoImpl anonymous = new AnonymousDemoImpl();
anonymous.display(new AnonymousDemo()
{
public void show()
{
System.out.println("Inside show method of anonymous class.");
System.out.println("y = " + y);
}
});
}
}
In above program we have created the anonymous class in our main method itself, and inside display method we are only calling show() method of interface which is implemented inside our anonymous class.
3rd Way to create anonymous class:
package com.dev21century;
interface AnonymousDemo
{
public void show();
}
public class AnonymousDemoImpl {
public static void main(String[] args)
{
{
AnonymousDemo anonymous = new AnonymousDemo(){
public void show()
{
System.out.println("Inside anonymous class.");
}
};
anonymous.show();
}
}
Output:
Inside anonymous class.
Above program is very easy way of implementing anonymous class. In all of the above programs, it is looking like we are creating an object of interface, but it is clearly not. We can never create instance of any interface. We are just creating a reference variable of interface and assigning anonymous class object in it.
No comments:
Post a Comment