What is Anonymous class? (Java)?

2006-01-22 1:05 am
The interviewer asked me What is Anonymous class? In what situation we have to use it? What is different between Inner Class and Anonymous class

回答 (2)

2006-01-22 4:50 am
✔ 最佳答案
Simply put, an anonymous class is a class without a name. In Java, this is possible when a class is defined "inline" - instead of giving it a name and then defining the class in a separate .java file, you just define it right then and there, in an inline block.

The typical use for an anonymous class is when you just need a "quickie" object which will you will never refer to again. An example of this is a Comparator implementation needed to build a sorting object.

An inner class need not be anonymous - you can fully define a class inside another class. But the inner class is only scoped within the outer class, even if it has a name.

For more details, read up on your Java documentation so you can be prepared for your interviewer. To fully understand inner and anonymous classes, you need to use them a few times, and a knowledgable interviewer will easily be able to tell if you really know about them.
2006-01-27 10:52 am
Inner Class
-----------
An inner class is where you define one class within another. You might do this where one class is tightly coupled to another class and there is no point in defining a new class.

Anonymous class
---------------
Anonymous class is also a inner class. It is actually a type of inner class without any class name. Anonymous inner classes are classes that are created in situation within a method and can only be used once, where they are defined

Anonymous inner classes are often used in setting up
listeners.
For example code check this site http://www.roseindia.net/javatutorials/anonymous_innerclassestutorial.shtml


收錄日期: 2021-04-25 13:05:49
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=1006012104701

檢視 Wayback Machine 備份