So, when looking into lambda expressions and using them to substitute anonymous inner classes for EventHandlers in Java, I came across a few anonymous inner classes that made me stop and think. For instance, when writing an anonymous inner class for something that normally implements ActionListener we write
myJButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
//DO SOMETHING
}
});
My confusion with this is, ActionListener is an interface so I thought it'd be necessary to do something like...
myJButton.addActionListener(new myButtonListener implements ActionListener() {
@Override
public void actionPerformed(ActionEvent e){
//DO SOMETHING
}
});
But this doesn't even compile. I guess the reason I though this is obviously if instead we use a private inner class, we use
private MyButtonListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
//DO SOMETHING
}
}
myJButton.addActionListener(new MyButtonListener());
So my questions are:
1) Why are we able to create an anonymous inner class directly from an interface rather than having to create one through a class that implements the interface?
2) Why am I unable to create an anonymous inner class that implements ActionListener instead of directly from it as I show in my second code snippet?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…