Wednesday, 17 May 2017

Create Marker/Tagging Interfaces

An interface with no methods is known as the marker interface. It provides some useful information to JVM/compiler so that JVM/compiler performs some special operations on it. It is used for better readability of code.
Few marker interfaces which are used in java are Random, Serializable, Clonnable etc.

Syntax:
public interface interface_name {
}

Example:
TierACollegeMarker.java
/**
 * This is marker interface for Tier A college.
 * @author rajesh.dixit
 */
public interface TierACollegeMarker {

}

IITD.java
/**
 * This class represents Tier A grade college.
 * @author rajesh.dixit
 */
public class IITD implements TierACollegeMarker {
     //Do something
}

Hindustan.java
/**
 * This class represents a, non-Tier A college.
 * @author rajesh.dixit
 */
public class Hindustan {
     //Do something
}

TestCollege.java

/**
 * This class is used to test the custom marker interface functionality.
 * @author rajesh.dixit
 */
public class TestCollege {
     static void tester(Object obj) {
           if (obj instanceof TierACollegeMarker) {
                System.out.println("Tier A college.");
           }
     }

     public static void main(String args[]) {
           IITD college1 = new IITD();
           Hindustan college2 = new Hindustan();

           /** test college objects.*/
           tester(college1);
           tester(college2);
     }
}

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...