Core Java Interviewfragen und Antworten
Question: What is Anonymous (inner) Class in java?Answer:An anonymous inner class can come useful when making an instance of an object which certain "extras" such as overloading methods, without having to actually subclass a class. I tend to use it as a shortcut for attaching an event listener:
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
// do something.
}
});
Using this method makes coding a little bit quicker, as I don't need to make an extra class that implements ActionListener - I can just instantiate an anonymous inner class without actually making a separate class. I only use this technique for "quick and dirty" tasks where making an entire class feels unnecessary. Having multiple anonymous inner classes that do exactly the same thing should be refactored to an actual class, be it an inner class or a separate class. |
Zum Wiederholen speichern
Speichere diesen Eintrag als Lesezeichen, markiere ihn als schwierig oder lege ihn in einem Wiederholungsset ab.
Melde dich an, um Lesezeichen, schwierige Fragen und Wiederholungssets zu speichern.
Ist das hilfreich? Ja Nein
Am hilfreichsten laut Nutzern:
- How could Java classes direct program messages to the system console, but error messages, say to a file?
- What are the differences between an interface and an abstract class?
- Why would you use a synchronized block vs. synchronized method?
- How can you force garbage collection?
- What are the differences between the methods sleep() and wait()?