'Anonymous Class'에 해당되는 글 1건

  1. 2007.12.18 Anonymous Class

Anonymous Class

software 2007. 12. 18. 17:30
 
public void aMethod() {
theButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("The action has occure");
}
}
);

}

public java.util.Enumeration enumerate() { // The anonymous class is defined as part of the return statement
return new java.util.Enumeration() { Linkable current; = head; { current = head; } // Replace constructor with an instance initializer public boolean hasMoreElements() { return (current != null); } public Object nextElement() { if (current == null) throw new java.util.NoSuchElementException(); Object value = current; current = current.getNext(); return value; } }; // Note the required semicolon: it terminates the return statement
}
클래스끝에 세미콜론이 있어야 한다는 점과 메소드안에서 선언된 변수를 참조하려면 final 이어야 함을 기억하자.

Why use anonymous classes?

As with local classes, objects instantiated from anonymous classes share many of the characteristics of objects instantiated from member classes.  However, in some cases, an anonymous class can be defined closer to its point of use than would be possible with a member class or a local class.  Once you become accustomed to the somewhat cryptic syntax used with anonymous classes, this can often lead to improved code readability.

Probably the most important benefit of anonymous classes has to do with accessing the members of enclosing classes.  Just like with member classes and local classes, methods of an anonymous class have direct access to all the members of the enclosing classes, including private members. Thus the use of anonymous classes can often eliminate the requirement to connect objects together via constructor parameters.

In addition, although not demonstrated in this lesson, as with local classes, objects of anonymous classes have access to final local variables that are declared within the scope of the anonymous class.

Can be particularly useful when ...

An anonymous class can be particularly useful in those cases where

  • There is no reason for an object of the anonymous class to exist in the absence of an object of the enclosing class.
  • There is no reason for an object of the anonymous class to exist outside a method of the enclosing class.
  • Methods of the object of the anonymous class need access to members of the object of the enclosing class.
  • Methods of the object of the anonymous class need access to final local variables and method parameters belonging to the method in which the anonymous class is defined.
  • Only one instance of the anonymous class is needed.
  • There is no need for the class to have a name that is accessible elsewhere in the program.


Anonymous Class 초기화 하기 - Instance initializer

http://www.javastudy.co.kr/docs/b612/basic/doc/study5.html

http://www.unix.org.ua/orelly/java-ent/jnut/ch03_12.htm

http://www.developer.com/java/other/article.php/3300881



Posted by ukmie
,