这是来自 Android 开发者网站的示例代码:
public void onClick(View v) {
new DownloadImageTask().execute("http://example.com/image.png");
}
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
/** The system calls this to perform work in a worker thread and
* delivers it the parameters given to AsyncTask.execute() */
protected Bitmap doInBackground(String... urls) {
return loadImageFromNetwork(urls[0]);
}
/** The system calls this to perform work in the UI thread and delivers
* the result from doInBackground() */
protected void onPostExecute(Bitmap result) {
mImageView.setImageBitmap(result);
}
}
这里,在 new DownloadImageTask().execute("http://example.com/image.png");
行中,new DownloadImageTask()
创建一个 DownloadImageTask
类的对象,还是创建一个扩展 DownloadImageTask
的匿名类?
比较:
在这段代码中,
public void onClick(View v) {
new Thread(new Runnable() {
public void run() {
Bitmap b = loadImageFromNetwork("http://example.com/image.png");
mImageView.setImageBitmap(b);
}
}).start();
}
已经创建并实例化了一个从 Thread 类派生的类的对象,但没有保存对它的引用(这使得它以后不能再次使用),而不是 Thread 类型的对象。以前的代码是怎么回事?
最佳答案
does
new DownloadImageTask()
create an object of theDownloadImageTask
class
是的。由于它是一个内部类,它将隐式地将当前封闭实例传递给(隐藏的)构造函数,但这就是该构造函数调用的所有甚至有点不寻常的地方。
匿名类创建表达式始终使用带有大括号的 new Something() { ... }
。
来自 section 15.9.1 of the JLS :
If the class instance creation expression ends in a class body, then the class being instantiated is an anonymous class.
关于java - 这也是匿名派生类的例子吗? (Java 基础知识),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18330351/