在我的 CS110 类(class)中,我们正在使用 Google Maps API 开发一个 Android 应用程序,其中一个概念是观察者设计模式。该设计模式教导了发布者和订阅者的概念。因此,当发布者的状态发生变化时,它会通知所有订阅者。在此示例中,LocationListener 是一个订阅者,但实现令人困惑。
代码 fragment 如下所示:
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
makeUseOfNewLocation(location);
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
LocationListener 是一个接口(interface),我的理解是你不能实例化一个接口(interface)。然而,LocationListener locationListener...
语句正在从 Interface
创建对象,这怎么可能?
此外,我的理解是这是一个匿名类。我不太确定我是否理解匿名类的含义。我理解匿名这个词的意思,但不是在类的上下文中。
如果您能帮助澄清这里发生的事情,我们将不胜感激。
最佳答案
这是来自 Oracle Java 官方站点的链接,其中对您所指的“匿名内部类”有很好的解释:http://docs.oracle.com/javase/tutorial/java/javaOO/innerclasses.html
另外,这里有一个关于堆栈溢出的类似问题的很好的链接:How are Anonymous (inner) classes used in Java?
关于java - 这段代码如何能够从接口(interface)中实例化一个新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21642956/