java - Anonymous classes and interfaces -


i illustrate issue use of example:

the addactionlistener method accepts actionlistener interface argument.

so when invoking method on object/component (such button) in order register listener object, through use of anonymous inner class, why need implement interface class? because definition, interfaces cannot instantiated, unless of course creating object of interface type implements abstract methods of interface?

i.e.

abutton.addactionlistener(new actionlistener() {     public void actionperformed(actionevent e) {         // stuff     } }); 

that is, through use of anonymous classes, can avoid explicitly making entire class implementing interface (as declared in header), rather instantiating object of interface (which definition of interface shouldn't possible) , implementing interface's abstract methods within anonymous class.

so possible instantiate object interface due fact @ point in time, contract needs fulfilled implement interface's methods, , in doing so, allows make object interface?

therefore, reason why can implement actionperformed() method of interface possible because of fact had instantiated object interface (which simultaneously requires fulfil contract of implementing abstract methods)? said 'implicitly' implementing interface in-situ instantiation of interface (as addactionlistener argument)?

you not instantiating interface.

you defining , instantiating actual, concrete class implements interface. need implement every method declared in interface, if wrote "normal" class implementing interface.

the anonymous class construct saves trouble of having name class going used in 1 specific place in code. if wanted have decided that. under covers same thing -- have defined class implement interface , instantiated class.


Comments

Popular posts from this blog

asp.net mvc - SSO between MVCForum and Umbraco7 -

Python Tkinter keyboard using bind -

ubuntu - Selenium Node Not Connecting to Hub, Not Opening Port -