2017-04-15 65 views

回答

2

是你正确的接口不能有构造函数但是你描述的是匿名类。在这一行中,您正在创建新类的对象,但没有扩展LocationListener的名称(并且它的实现位于大括号之间)。 如果你想了解一些更多关于匿名类看这里:https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html

+0

感谢您的回复,但为什么它需要一个构造函数(LocationListener())? –

1

这是匿名类的方法。为了说清楚,这里是一个例子。

interface Animal { 
    public void cry(); 
} 

要创建Animal实例的对象,您需要先实现动物接口。

class Lion implements Animal { 
    public void cry() { 
     System.out.println("Roar"); 
    } 
} 

然后,使用通常的方法创建一个对象:

Animal theLion = new Lion(); 

另一种方法是创建使用匿名类Animal对象。现在

Animal theTiger = new Animal() { 
    public void cry() { 
     System.out.println("Grrr"); 
    } 
} 

,无论对象应该能够调用cry方法:

theLion.cry(); 
theTiger.cry(); 

干杯!

+0

感谢您的回复,但为什么它需要构造函数(Animal()),如果在接口中没有定义构造函数? –

+0

,因为Anonymous类是声明类如Lion类的简写。 – user1506104

相关问题