本文介绍了匿名类如何使用“扩展”?或“实施”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

匿名类如何扩展超类或实现接口?

How can an anonymous class extend a superclass or implement an interface?

推荐答案

匿名类必须扩展或实现某些东西,就像任何其他Java类一样,即使它只是 java.lang.Object

Anonymous classes must extend or implement something, like any other Java class, even if it's just java.lang.Object.

例如:

Runnable r = new Runnable() {
   public void run() { ... }
};

此处, r 是一个对象实现 Runnable 的匿名类。

Here, r is an object of an anonymous class which implements Runnable.

匿名类可以使用相同的语法扩展另一个类:

An anonymous class can extend another class using the same syntax:

SomeClass x = new SomeClass() {
   ...
};

你不能做的是实现多个接口。你需要一个命名类来做到这一点。但是,匿名内部类和命名类都不能扩展多个类。

What you can't do is implement more than one interface. You need a named class to do that. Neither an anonymous inner class, nor a named class, however, can extend more than one class.

这篇关于匿名类如何使用“扩展”?或“实施”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 17:31