Monday, March 28, 2011

Marker interfaces in java

Marker interfaces in java

The marker interface is an interface that provides run-time type information about objects.

Dear reader,
Recently an interviewer asked me to give the use of marker interfaces and how to write my own.
some uses you know: Serializable, Cloneable so not repeating here.

Other real time example: Suppose in a company project, there are so many Java API, we want to process/extend
some functionalities to only those API which uses our own marker interface like My_Company_Name_Interface.

If you know then no need to read further, else I will suggest you to read once this:


//MarkerInterface.java (our marker interface)
package markerInterface;

public interface MarkerInterface {
//This interface is like other marker interfaces
//Cloneable, Serializable which don't have any method declaration
}



//MarkerInterfaceImpl.java (our API who implements this interface)
package markerInterface;

public class MarkerInterfaceImpl implements MarkerInterface{
public MarkerInterfaceImpl(){}
}



//MarkerInterfaceNotImpl.java (our other API who doesn't implement this interface)
package markerInterface;

public class MarkerInterfaceNotImpl {
public MarkerInterfaceNotImpl(){}
}



//TestMarker.java (Main program to test)
package markerInterface;

public class TestMarker {
public static void main(String[] args) {
MarkerInterfaceImpl markerImpl=new MarkerInterfaceImpl();
MarkerInterfaceNotImpl markerNotImpl=new MarkerInterfaceNotImpl();

System.out.println(markerImpl instanceof MarkerInterface);
System.out.println(markerNotImpl instanceof MarkerInterface);

if(markerImpl instanceof MarkerInterface){ //This is true
//do something for your own API
}
else {
//do something for other API
}
}
}

//Output:
true
false

//Best use of "instanceof" operator in Java.

No comments:

Post a Comment