The use of the Java direct new interface

Source: Internet
Author: User

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

1 package contract;2 3 public interface Isay {4 void SayHello (); 5}

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

  1 package jimmy;  2 import contract. Isay;  3 public class program {  4     public  static void main (String[] args)  {  5          isay say = new isay ()  {            6             public  void sayhello ()  {  7                  system.out.println ("hello java!");   8             }  9          }; 10     } 11 } 

At first glance, as if in "without providing interface implementation, a direct new interface instance", for C#er, there is a bright to destroy the three views.

Fortunately this is just an illusion, observing the class output in the bin directory, you will find a similar program1.CLassof thetextpieces,asFruitAnti-compilationtranslationViewObserveaunder,HairnowOriginalcome tois acompilationtranslationDevicefromMovingHealthintoaaclassP Rog Ram1:

1 package Jimmy; 2 3 import contract.  Isay;  4 Import Java.io.PrintStream; 5 6 class Program$1 7 implements Isay 8 {9 public void SayHello () Ten {one System.out.println ("Hello java!" ); 12} 13}

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.

Java: Using anonymous class direct new interface

The use of the Java 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.