Tuesday, June 4, 2019

Marker Interface

Q- What are the marker interfaces in Java?
A marker interface is an interface which have  no method declaration inside it. or we can say more simply, it is an empty interface in Java, are called a marker interface.
Examples Serializable , Cloneable and Remote interfaces. These are used to indicate to Java compiler so that it can add special behaviour to the class implementing it.
A marker interface is also called a  tagging or tag  interface.

Q- Why is marker interface empty?
As these are used to indicate to Java compiler, so that it can add special behaviour to the class implementing it. and they do nothing.

Q- Can we write marker interface Java? Or Where do we use marker interface in Java?
Java have built-in marker interface like Serializable , Clonnable, Remote interface & EventListner etc that are understand by JVM.
Yes we can create our own marker interface, but it can't do nothing with JVM, we can add some checks using instanceOf. To identify that more than one classes have same instance. so it's easy to categorize in our code.

Example:- 

interface CategoryA {
}

interface CategoryB {
 }

Class ProductA implements CategoryA{

 public void m1(){
  System.out.println("m1");
 }
}

Class ProductB implements CategoryA{

 public void m2(){
  System.out.println("m2");
 }
}

Class ProductC implements CategoryB{

 public void m3(){
  System.out.println("m3");
 }
}

Class ProductD implements CategoryB{

 public void m4(){
  System.out.println("m3");
 }
}

public class TestMain {
 public static void main(String arg[]) {
  ProductA obj = new ProductA();
  ProductB obj = new ProductB();
  ProductC obj = new ProductC();
  ProductD obj = new ProductD();

  // obj can be the object of any product

  if (obj instanceof CategoryA) {
   System.out.println("Product of CategoryA");
  }
  if (obj instanceof CategoryB) {
   System.out.println("Product of CategoryB");
  }
 }
}

No comments:

Post a Comment