在java中创建接口对象 [英] Creating interface objects in java
本文介绍了在java中创建接口对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我遇到了一些Java代码:
I encountered some Java code:
public class LocationProvider {
public interface LocationCallback {
public void handleNewLocation(Location location);
}
// class constructor
public LocationProvider(Context context, LocationCallback callback){
...
}
}
我第一次遇到一个带有类型参数的构造函数或方法是一个界面。是否可以创建接口对象?你可以像常规对象一样使用它们吗?
For the first time in Java, I am encountering a constructor or method with an argument of a "type" that is an interface. Is it possible to create objects of interfaces ? Can you use them like regular objects ?
在C ++中我知道不可能创建抽象类的对象。
In C++ I know it's not possible to create objects of an abstract class.
推荐答案
好的。让我们来看看基础:)。
Ok. Lets go over the basics :).
class A implements X{// where X is an interface
}
class B implements X{
}
现在,我们有
void someMethodAcceptingInterfaceX(X someInstanceOfX)
{
//do something
}
现在你可以做,
X a = new A();
X b = new B();
someMethodAcceptingInterfaceX(a);
someMethodAcceptingInterfaceX(b);
即,您可以传递任何接口X 。实现接口的任何类都被称为接口的实例(在更广泛的上下文中)。
i.e, you can pass anything which is interface X. Any class which implements an interface is said to be an instance of that interface (in a broader context).
这篇关于在java中创建接口对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文