In java you can use Anonymous Classes and Anonymous Interfaces.
Anonymous classes
class MyMessage { public class TestAnonymousClass { public static void main(String[] args) { MyMessage m = new MyMessage(); void showGeneralMessage(MyMessage msg) { |
The Bold source shows how to create the anonymous class. As you can see it’s not so anonymous as we expected, it’s just the name that is anonymous.
In anonymous classes the only think we can do it’s to instantiate an existing class, and override or add some methods. What are we really doing is extending another class(in our example we are extending “MyMessage”) with the possibility to override or add new methods.
If you run the code above the output will be:
Original message Override message |
Anonymous Classes with interfaces
interface MyMessage { public class TestAnonymousClass { public static void main(String[] args) { tac.showGeneralMessage(new MyMessage() { void showGeneralMessage(MyMessage msg) { |
Now with interfaces, you can observe that the syntax it’s the same, but we are creating a class by “implementing” the interface MyMessage.
Look that I only changed the MyMessage class to be and interface, but the remaining code is still the same and works with the same behavior (ok, now the output doesn’t have the “Original Message”, because we don’t have one! We lost it when we changed the class to be an interface.)
Hope it helps you in your projects, to implement callbacks, using swing components to register listeners, etc..
Technorati Tags: Anonymous,Java,Classes,Interfaces
Windows Live Tags: Anonymous,Java,Classes,Interfaces
WordPress Tags: Anonymous,Java,Classes,Interfaces