Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Java
Expertise: Intermediate
Dec 18, 1998

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 here
4.       }
5.     }
6. 
7. 
8.     public class AnonymousSubClassExample {
9.       public void testAnonymousSubClass() {
10.      new SuperClass() {
11.        public void superMethod() {
12.          // Overridden superMethod implementation here
13.        }
14. 
15.        public anotherMethod() {
16.          // anotherMethod implementation here
17.        }
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().
Ajit Sagar
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date