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:
Share on facebook
Share on twitter
Share on linkedin


The Latest

technology leadership

Why the World Needs More Technology Leadership

As a fact, technology has touched every single aspect of our lives. And there are some technology giants in today’s world which have been frequently opined to have a strong influence on recent overall technological influence. Moreover, those tech giants have popular technology leaders leading the companies toward achieving greatness.

iOS app development

The Future of iOS App Development: Trends to Watch

When it launched in 2008, the Apple App Store only had 500 apps available. By the first quarter of 2022, the store had about 2.18 million iOS-exclusive apps. Average monthly app releases for the platform reached 34,000 in the first half of 2022, indicating rapid growth in iOS app development.

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job