Posts which you will also like.

Thursday, September 13, 2012

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
Pointing up
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).


Fingers crossed



//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

1 comment:

  1. nice blog checkout mine at
    http://www.definingwords.blogspot.com
    feel free to leave a comment

    ReplyDelete

Your comment may wait for moderation....

DMCA.com Protected by Copyscape Online Plagiarism Tool