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