Subclassing Anonymously

Subclassing Anonymously

Anonymous classes in Java are defined inside another class (i.e., they are inner classes), do not have a name, and are defined inside a Java expression such as an assignment or a method call. Another not so obvious characteristic of anonymous classes is that they are subclasses of the class that is used to instantiate them. For example, the following code gives an example of an anonymous class declaration.

 1.     class SuperClass {2.       public void superMethod() {3.       // superMethod implementation here4.       }5.     }6. 7. 8.     public class AnonymousSubClassExample {9.       public void testAnonymousSubClass() {10.      new SuperClass() {11.        public void superMethod() {12.          // Overridden superMethod implementation here13.        }14. 15.        public anotherMethod() {16.          // anotherMethod implementation here17.        }18.      }19.     }20.  }

Lines 1-5 declare the super class of the anonymous class, which implements a single method called superMethod(). In lines 8-20, an anonymous class is declared inside a method. The class AnonymousSubClassExample defines a single method called testAnonymousSubClass(). This method defines an anonymous class on line 10. Note that it does not have a name. The anonymous class has two methods called superMethod() and anotherMethod(). The superMethod() overrides the method in the SuperClass. The anotherMethod() is a brand new method that is local to the new anonymous class. The anonymous class overrides a method in SuperClass and also extends SuperClass’s functionality by adding another method. The difference between this class and a regular subclass is that the scope of the anonymous class is limited to the method testAnonymousSubClass().


Share the Post: