Tue, Nov 19, 2019
Read in 2 minutes
Anonymous inner class is an inner class without a name. These Anonymous inner classes are defined and instantiated at the same time. This class is defined in the expression and it starts with a new keyword.
If you want to know about inner classes, Please have a glance at Why Inner Calsses
What are the special features in the inner class :
package explore.innerclass;
package explore.innerclass;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
public class AnonymousClassDemo {
public void createApp() {
JFrame frame =new JFrame();
frame.setTitle("App");
frame.setSize(500, 500);
JButton button =new JButton("click");
button.setToolTipText("button");
button.setBounds(150,95,95,40);
JTextArea text =new JTextArea();
frame.add(button);
frame.add(text);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
//addMouseListener adds the listener.
//MouseAdapter is a abstract class and its not possible to create object.
//So with anonymous class you can create instance for the abstract class.
button.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
text.setText("You learnt anonymous class");
}
});
}
public static void main(String[] args) {
AnonymousClassDemo c =new AnonymousClassDemo();
c.createApp();
}
}
Points to be Remembered :