Day_Dreamer Day_Dreamer - 9 months ago 65
Java Question

creating interface objects in java

I encountered some java code:

public abstract interface LocationCallback {
public void handleNewLocation(Location location);
} // declared inside LocationProvider class

public LocationProvider(Context context, LocationCallback callback) // class c'tor

For the first time in java, I encountered c'tor the one of its arguements is an object of ""type" that is abstarct interface. Is it possible to create object of Class that is Interface? you use them like regular objects?

In c++ I know it's not possible to create object of abstract clasd


Ok. Lets go over the basics :).

class A implements X{// where X is an interface

class B implements X{

now, we have

void someMethodAcceptingInterfaceX(X someInstanceOfX)
//do something

Now you can do,

X a = new A();
X b = new B();

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).