18 Ekim 2014 Cumartesi

Anonymous Classes in JAVA

What does this mean?
An anonymous class is just what its name imples -- it has no name. It combines the class declaration and the creation of an instance of the class in one step.
Probably most of the classes you have developed so far have been named classes such as Queue or Circle. Each of these classes contained a full definition; you could instantiate objects from any of these classes.
When defining an anonymous class, the definition and object instantiation is done all in one step. The class itself has no name (this is why it's anonymous) and this is the only way an object can be instantiated.
Since anonymous classes have no name, objects can not be instantiated from outside the class in which the anonymous class is defined. In fact, an anonymous object can only be instantiated from within the same scope in which it is defined.



Why use an anonymous class?
Anonymous classes can be time-savers and reduce the number of .java files necessary to define an application. You may have a class that is only used in a specific situation such as a Comparator. This allows an "on the fly" creation of an object.
You may find you prefer to use anonymous classes; many people use them extensively to implement listeners on GUIs.
What are these classes with unusual names?
Just because a class is anonymously defined, it's still a class and a corresponding class file needs to be created.
When you compile a class that contains an anonymous class definition, the compiler will create separate class files named
    ClassName$SomeNumber
where ClassName is the name of the class in which this anonymous class is defined, and SomeNumber is a the sequence number for the anonymous class.
In other words, if you implement a single anonymous class within the class MyAnonymousTest, the compiler will generate the files MyAnonymousTest.class and MyAnonymousTest$1.class.
If you implement two anonymous classes in the same class, MyAnonymousTest$2.class will also be created.
The Syntax for Anonymous Class Definitions
This example demonstrates an anonymous class definition for a comparator that is passed to the sort() method in the Collections class. Assume that aList is a valid List of data that is to be sorted.
    Collections.sort (aList,
      new Comparator () { // implements the IF
        public int compare (ObjectType o1, ObjectType o2 ) throws ..{
          .... implementation for compare() 
        } // end of compare() 
      } // end of Comparator implementation
    ); // closed paren for sort() and end of statement semicolon

Rules:

      An anonymous class must always extend a super class or implement an interface but it cannot have an explicit extends or implements clause.
      An anonymous class must implement all the abstract methods in the super class or the interface.
      An anonymous class always uses the default constructor from the super class to create an instance.

Hiç yorum yok: