일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
- asp.net
- SpringSource Tool Suite
- Maven
- MANTIS
- varags
- Bootstrap
- html
- Java
- WebView
- Android
- MSsql
- Web Service
- 웹뷰
- scrollView
- STS
- 이클립스
- Eclipse
- TextBox
- jsp
- C#
- 컬럼명
- Apache Lucene
- 웹 서비스
- Redirect
- javascript
- 안드로이드
- 자바
- 자바스크립트
- decompiler
- MS-SQL
- Today
- Total
bboks.net™
Java Anonymous Class 본문
A type of inner class that has no name that you define right in the middle of a method (where static init blocks and instance init blocks count as methods). You define it, and create an object of that type as a parameter all in one line. An anonymous class is defined and instantiated in a single succinct expression using the new operator.Used for creating simple delegate callback objects.These anonymous inner classes can access the static and instance variables of the enclosing outer class.
Instead of passing arguments to a constructor, your inner class methods can reach out and grab what they need directly from local variables in the enclosing method. The other technique is to use an instance initialiser block. You are only allowed one per anonymous inner class.
Syntax for Anonymous Classes
new class-name ( [ argument-list ] ) { class-body }
package Vinay; public class VinayMain { public static void main(String[] args) { // Here is where the anonymous class is defined and instantiated // Runnable vinayrun = new Runnable() { int Total = 0; public void run() { for (int i=0; i<10000000; i++) { Total++; } System.out.println(Integer.toString(Total)); } }; vinayrun.run(); } }
create an instance, named vinayrun , of a nameless (anonymous) class which implements the java.lang.Runnable interface.And we are calling the run mehtod of anonymous class through vinayrun object.
Drawback– The big drawback with anonymous classes is they can’t have explicit constructors. You can’t pass them any parameters when they are instantiated.
Benefits of Anonymous Classes
The key benefit of an anonymous class is encapsulation (or clutter reduction). An anonymous class is, in a sense, the ultimate in private object oriented encapsulation. It is defined exactly where it is needed, it can never be used anywhere else, and it has totally local scope.One final key benefit of anonymous classes is that they have access to all data and methods of their containing classes, including private members; meaning that for small highly localized tasks, they may require less initialization.
References -
http://ssmela.googlepages.com/AnonymousClassesinJava.pdf
http://mindprod.com/jgloss/anonymousclasses.html
[출처] techartifact.com