我已经看到,构造函数不是一个界面内允许的,但是这是怎么允许?:为什么LocationListener有一个构造函数,如果它是一个接口?
LocationListener的=新LocationListener的(){ 等}
我已经看到,构造函数不是一个界面内允许的,但是这是怎么允许?:为什么LocationListener有一个构造函数,如果它是一个接口?
LocationListener的=新LocationListener的(){ 等}
是你正确的接口不能有构造函数但是你描述的是匿名类。在这一行中,您正在创建新类的对象,但没有扩展LocationListener的名称(并且它的实现位于大括号之间)。 如果你想了解一些更多关于匿名类看这里:https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html
这是匿名类的方法。为了说清楚,这里是一个例子。
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();
干杯!
感谢您的回复,但为什么它需要构造函数(Animal()),如果在接口中没有定义构造函数? –
,因为Anonymous类是声明类如Lion类的简写。 – user1506104
感谢您的回复,但为什么它需要一个构造函数(LocationListener())? –