oop - Clarification needed on Concept of a listener anonymous class in java -


i'm new java. purpose of listener anonymous inner class design? heard anonymous classes used listeners in java. , no 1 creates inner classes or static inner classes. i'm not sure means. 1 explain these concepts bit? listener design , how created via anonymous class.

thank in advance.

an anonymous listener this:

mycontrol.addactionlistener(new actionlistener() {     public void actionperformed(actionevent e) {         // handle event     } }); 

using inner class accomplish same goal this:

public void init() {     mycontrol.addactionlistener(new myactionlistener()); }  private class myactionlistener implements actionlistener {     public void actionperformed(actionevent e)     {         // handle event     } } 

now consider 2 in scope of larger program. anonymous listener still right there @ spot you're adding it. inner class may somewhere else in source file entirely. ide, difference can minimized (such members browser), there need entirely new class you're going use once?

of course, depending on exact needs of application, separate class might in fact better choice. if, example, have many listeners differ little bit, construct along these lines:

public void init() {     mycontrol1.addactionlistener(new myactionlistener("foo"));     mycontrol2.addactionlistener(new myactionlistener("bar"));     mycontrol3.addactionlistener(new myactionlistener("baz")); }  private class myactionlistener implements actionlistener {     private string word;      public myactionlistener(string word)     {         this.word = word;     }      public void actionperformed(actionevent e)     {         // handle event         system.out.println(word);     } } 

as far static classes go: in java, inner class can marked static, , prevent having reference instance of enclosing class. (for example, myprogram.mystaticclass not able access members of myprogram weren't static, unless creates new instance of myprogram.) may separation-of-concerns, doesn't change when comes listeners.


Comments

Popular posts from this blog

python - Subclassed QStyledItemDelegate ignores Stylesheet -

java - HttpClient 3.1 Connection pooling vs HttpClient 4.3.2 -

SQL: Divide the sum of values in one table with the count of rows in another -