Why we need anonymous class in java? When we have to use it and what's the usage? Is it important to use that class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why we need anonymous class in java? When we have to use it and what's the usage? Is it important to use that class?

I started learning Java.. I'm just a beginner now.. I just need clarification.. can anyone give clear answer for my question..

6th Oct 2017, 1:42 PM
Priya Srinivasan
Priya Srinivasan - avatar
2 Answers
+ 2
Anonymous classes are often used in GUI programms for action handling or userinterface stuff. Through anonymous classes it is possible to make the code shorter and in some cases more readable. You should use it if you only need a class ONE time. eg. button.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { // do something } }); this is a good example because the action listener in this form is only needed one time for that perticular button + you instantly see what action listener does instead of writing an own class only for one use. hope i could clarify anonymous classes for you
6th Oct 2017, 6:02 PM
Chrizzhigh
Chrizzhigh - avatar
+ 1
great..! i got a clear picture now.. now i figured it out..!!! thank u for your answer.. it's really valuable for me...!!!
7th Oct 2017, 3:55 AM
Priya Srinivasan
Priya Srinivasan - avatar