"Marker interface is a interface which has no methods to implement"
This is what I learn in my graduation. This is quite strange that why I should implement such stupid interface when it doesn't have a single method. With my target of finishing exam and my over smartness, that time I assumed that "Sun" guys gone mad and done this stupidity. I scored good marks....
Now when I tried to dig the purpose, the truth is different.
The Marker interface is just a way to mark class that it has certain capability. This mechanism is also referred as "marker interface pattern". This is really important concept as it provides a means to associate metadata with a class where the language does not have explicit support for such metadata. This pattern is supported by all those languages which provide run time type identification of an object.
Example of marker Interface.
java,lang.Cloneable
java,io.Serializable
java.util.EventListener
java,io.Serializable
java.util.EventListener
Some key Notes:
- We can implement our own custom marker interface. e.g. I have some abstract financial classes where currency is important thing. I don't want to handle that which currency need to be used . I may come up with idea of having different marker interface as RupeesMarker, DollarMarker or EuroMarker, and then I will leave on programmers who inherits my class, to implement any one of above marker interface for required currency. Of course I have already handled the logic in abstract class about for-matter to be used depend on type of marker interface used.
- The problem with marker interface is once you implement if for some class that tag is automatically inherited by all subclasses, and in this case suppose you don't want to mark it for a purpose superclass did, you don't have a way to "unimplement" the marker.
Example:
Interface: BossMarker.java
public interface BossMarker {
// My whole purpose in life is to tag, all those classes who implement me, as Boss
}
// My whole purpose in life is to tag, all those classes who implement me, as Boss
}
Abstract Class: Boss.java
public abstract class Boss implements BossMarker {
{
if(this instanceof BossMarker)
System.out.println("Hey I am a " + this.getClass() + " Tagged as Boss");
}
}
{
if(this instanceof BossMarker)
System.out.println("Hey I am a " + this.getClass() + " Tagged as Boss");
}
}
Testing Class: Person.java
public class Person extends Boss {
public static void main(String arg[]){
Person p = new Person();
}
}
public static void main(String arg[]){
Person p = new Person();
}
}
Output:
Hey I am a class Person Tagged as Boss
Note: If you disagree to any of above mentioned points, feel free to comment, I will correct if required.
No comments:
Post a Comment