For example in this code snippet:
c.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entry event: " + e
+ " on button: " + buttonLabel);
}
});
Is the code block inside the braces of addMouseListener declaring an anonymous class of MouseAdapter() and then the whole thing is called a 'function callback', or am I mixing up the terms? What is the difference?
No.
You can implement callback in several ways in Java, anonymous class is a common way, especially before Java 8.
In OO , callback is relative to a principle called Hollywood Principle: "Don't call us, we'll call you". Check here for more information about callback in java.
In Java, we only have class/object, so, callbacks will always be implemented using objects in Java. Thus, I don't think we should call it "function callback" in Java, instead, callback object may be more appropriate.
We pass a callback object to another object, so that that object can call some specific method on the callback object when that object thinks it is time. In your case, you pass a MouseAdapter instance to your c. And c will call the method mouseEntered of the passed MouseAdapter instance when mouse is entered(c thinks it is time). So, we don't explicitly call c'method relative to mouse entered like:
while(true){
if(mouce_entered){
mouseEntered();
}
wait_for_mouseentered_event();
}
Instead, c does all this job, we only need to pass a callback object to him and let c control the logic flow.
1.So, actually, the first way to implement this callback is you declare a class extends MouseAdapter
public class YourMouseListener extends MouseAdapter()
{
public void mouseEntered(MouseEvent e) { ... }
}
then create an instance and pass to it:
c.addMouseListener(new YourMouseListener());
2.To minimize code and class declared, Java enable you to use anonymous class to achieve callback like:
c.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
System.out.println("Mouse entry event: " + e
+ " on button: " + buttonLabel);
}
});
3.In Java 8, we have lambda expression, we can replace some anonymous class into a more concise lambada expression, but this is limited on function interface,which only have one method.
//Old way:
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("The button was clicked using old fashion code!");
}
});
//New way:
button.addActionListener( (e) -> {
System.out.println("The button was clicked. From lambda expressions !");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With