Tag: Anonymous

Anonymous Java Classes and Interfaces

In java you can use Anonymous Classes and Anonymous Interfaces.

Anonymous classes

class MyMessage {
public void printMessage() {
System.out.println("Original message");
}
}

public class TestAnonymousClass {

public static void main(String[] args) {
TestAnonymousClass tac = new TestAnonymousClass();

MyMessage m = new MyMessage();
m.printMessage();

tac.showGeneralMessage(new MyMessage() {
public void printMessage() {
System.out.println("Override message");
}
}
);
}

void showGeneralMessage(MyMessage msg) {
msg.printMessage();
}
}

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 {
void printMessage();
}

public class TestAnonymousClass {

public static void main(String[] args) {
TestAnonymousClass tac = new TestAnonymousClass();

tac.showGeneralMessage(new MyMessage() {
public void printMessage() {
System.out.println("Override message");
}
}
);
}

void showGeneralMessage(MyMessage msg) {
msg.printMessage();
}
}

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: ,,,

Windows Live Tags: Anonymous,Java,Classes,Interfaces

WordPress Tags: Anonymous,Java,Classes,Interfaces

Bad Behavior has blocked 170 access attempts in the last 7 days.

Hyper Smash