Java Anonymous inner class A class with no name is an anonymous inner class in java. enables you to make your code more concise. declares and instantiates a class at the same time. local classes except that they do not have a name. Use them if you need to use a local class only once.
If you have to override method of class or interface. Can be created by two ways: Class (may be abstract or concrete). Interface
A class is created and its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method. An object of Anonymous class is created that is referred by p reference variable of Person type.
A class is created and its name is decided by the compiler which implements the Eatable interface and provides the implementation of the eat() method. An object of Anonymous class is created that is referred by p reference variable of Eatable type.
Interfaces as Callbacks A callback is a situation where you'd like to pass a reference to some behavior and have another object invoke it later.
interface TextUpdateable { receiveText( String text ); } class TickerTape implements TextUpdateable { TextSource source; init() { source = new TextSource( this ); ... public receiveText( String text ) { scrollText( text ): class TextSource { TextUpdateable receiver; TextSource( TextUpdateable r ) { receiver = r; private sendText( String s ) { receiver.receiveText( s );
TextSource object will send any new text data TextSource stores a reference to a TickerTape object, but then we could never use our TextSource to send data to other kind of objects. A more elegant solution is to have TextSource store a reference to an interface type, TextUpdateable. TextSource really cares about is finding the right method to invoke to send text. TickerTape object simply passes a reference to itself as the callback for text updates, and the source invokes its receiveText() method as necessary.