Java: Using anonymous class direct new interface

Source: Internet
Author: User

The anonymous class in Java has a magical usage, as shown in the following code example:

 Package contract;  Public Interface Isay {    void  SayHello ();}

Above is a simple interface, below is how to use:

 Package Jimmy; Import contract. Isay;  Public class Program {    publicstaticvoid  main (string[] args) {          New  Isay () {                      publicvoid  SayHello () {                System.out.println ( "Hello java!" );            }        };    }}

At first glance, it seems as if "an interface instance is new directly" without providing an interface implementation.

Fortunately, it's just an illusion.observing the class output in the bin directory, you will find a similar program1.CLASSOfTextThing,Such asFruitAnti -CodecTranslatedViewSrebrenicaOneUnder,HairIsOriginalToIsCodecTranslatedManagerSelf -Move Sheng One class pr< Span id= "mathjax-span-98" class= "Mi" >og ra m 1:

 Package Jimmy; Import contract. Isay; Import Java.io.PrintStream; class Implements isay{  publicvoid  SayHello ()  {    System.out.println (" Hello java! " );  }}

If there are situations where you just need to create an implementation class for an interface temporarily, the "tricks" above can be used to simplify the code.

Http://www.cnblogs.com/yjmyzz/p/3448330.html

Java: Using anonymous class direct new interface

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.