Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Tutorial on Anonymous Inner Class


An Anonymous inner Class is a very strange type of inner class.It can be created on the fly when needed and It can also be defined inside method argument!.
We will cover all the details about anonymous inner class in this blog post so continue reading.
As the name suggests anonymous inner classes do not have any name so how would you recognize a inner class? Anonymous inner classes are recognized by their parent’s type.Here parent could be either a class or interface.Basically anonymous inner class can be categorized into two types:
  • As a class providing implementation to a predefined interface.
  • As a class providing implementation to a predefined class or a abstract class
Now we will see both methods

class Test{
public void doTesting(){
System.out.println("Testing is on the way!");
}
}
public class InnerJ{
Test t=new Test(){
public void doTesting(){
System.out.println("Testing completed!");
}
};//watch out for semicolon
}



Here what we are saying basically  is,that create a anonymous class(without any name) which is a subclass of type Test(extends Test) and declare a reference variable of type Test to hold that anonymous class object since at the same time we are instantiating that anonymous inner class(see the new key word in InnerJ).






//Now same thing with interface 
interface Test{
void doTesting();
}
public class InnerJ{

//Beware this not instantiation of interface !
Test t=new Test(){
public void doTesting(){
System.out.println("Testing completed!");
}
};//watch out for semicolon
}


here instead of saying extends we say implements and every thing is same.


Restrictions on anonymous inner class:



  • Anonymous inner classes can implement only one interface


  • Anonymous inner classes can either extends a class or implement an interface at a time



This post first appeared on TechSoftEng, please read the originial post: here

Share the post

Java Tutorial on Anonymous Inner Class

×

Subscribe to Techsofteng

Get updates delivered right to your inbox!

Thank you for your subscription

×