java - 这也是匿名派生类的例子吗? (Java 基础知识)

标签 java android

这是来自 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 the DownloadImageTask 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/

相关文章:

java - 小程序运行时按钮和滚动条不响应

java - 打印二叉树中节点的祖先

java - Android 上的犀牛

android - 将 MySQL 数据库导入到 android SQLite 数据库

java - Android Canvas,具有不同缩放量的多个路径

java - 在已经从文本中随机选择一个单词后,如何从文本文件中打乱单词

java - Xalan Transformer 转换破坏了 Unicode 6 星体字符

java - 使用 Java 通过 HTTP 发送文件内容

android - 通过XML将所有TextView设置为不可见

android - MapController 调用在事件处理程序内部不起作用?