JaVa
   

Defining on the Fly

Although this aspect of coding is not completely conventional, it can make code neater for one-off defining implementations of members of a class. Okay, perhaps we should explain a little. Perhaps you want to have just a special type of alien that simply contains its own version of the speak method but only require one that might not be worth creating a whole new class for. In Java, you can create this new type of Alien object as follows.

Alien newAlien = new Alien("Dak-DakDakDak")
 {
 public void speak()
 {
 System.out.println("No comment");
 }
 };


This method is most notably used for supplying your own methods for event handling, which we will look at in s 9 and 10. You should note that this method is just another way to define members of a class "on the fly" as opposed to perhaps declaring a nested class that would, in this example, extend the Alien class and then provide the defining method in there. This technique should simply be seen as an alternative way of doing this. Note that this can also be applied to defining interface methods on the fly for interface objects, though all interface methods would have to be defined in this case.

JaVa
   
Comments