Pages

Tuesday, May 12, 2009

Java Marker Interface

Share it Please

Writing a marker interface is pretty much simple in java. As we know that a marker interface does not contain any methods . But still it holds some functionality . Like serialization interface which does not contain any methods but holds the functionality as it makes the user defined object to move on the wire. Is it possible to write our own marker interface in java ?,

Lets write a sample marker interface , a marker interface in java is much like a normal interface with no methods .

Public interface JavaBook { }

Public interface CBook{ }

Public interface C++Book{ }

Now you can see that I have written the marker interfaces, but how to make these interfaces perform some functionality. Now consider I have a library which contains some books like java, c and c++. Now if I want to get books related to java or related to c++ . How can I do that.

So when ever iam going to create a new book in library iam going to implement the marker interfaces , like

Class Java2Java implements JavaBook { }

Class C2C implements CBook { }

Class CplusPlus implements C++Book { }

So now I have java, c and C++ books in my library which implements the marker interface.

Now when I want a book of java or any other related type, I will just write a class which checks the instance of all the books with the related interfaces, so if I need java related books, I will get all the books from the library and check them against the JavaBook interface.

Class TestClass {

Public static void main(String sr[]){

List javaBooks=new ArrayList();

For(Iterator it=allBooks.iterator();it.hasNext();){

Book obtainedBook=(Book)it.next();

If(obtainedBook instanceof JavaBook){
javaBooks.add(obtainedBook);

}

}

You can see that we have given our marker interface some functionality. Similarly java.io.Serializable marker interface works in the similar way. When ever we are executing some thing , the jvm will check the current object against java.io.Serializable interface to make it move along the wire.if it implements it can move along the wire , it not it doesnot move.

This is how marker interfaces works.

4 comments :

  1. Jagadeesh,

    Looks good article. I just have one suggestion. Instead of taking 3 marker interface examples(JavaBook, CBook, C++Book), just take one marker interface and explain. I think it will look more clear.

    Venu.

    ReplyDelete
  2. Very Good explanation..

    Ramu

    ReplyDelete
  3. Very Good Explanation

    ReplyDelete
  4. marker interface in java
    a kind of interface which has no method is known as marker interface. Serializable, Clonnable is the example of marker interface

    ReplyDelete