Hilton D
Coder
For example, let's say I have a class hierarchy of animals, and I want to mark some of them as endangered. I can create a marker interface called "Endangered" that I saw in a similar article by scaler like this:
Then I can have several classes that implement the Endangered interface:
I can now use the Endangered interface to declare instances of the Tiger and Panda classes as endangered:
However, there are certain possible concerns to consider while employing marker interfaces:
Because Java does not enable multiple inheritances, a class can only implement one marker interface at a time. This may restrict the design's flexibility and extension.
Code:
public interface Endangered {
// empty interface, no methods declared
}
Code:
public class Tiger implements Endangered {
// class implementation
}
public class Panda implements Endangered {
// class implementation
}
Code:
Tiger tiger = new Tiger();
if (tiger instanceof Endangered) {
// tiger is endangered
}
Panda panda = new Panda();
if (panda instanceof Endangered) {
// panda is endangered
}
Because Java does not enable multiple inheritances, a class can only implement one marker interface at a time. This may restrict the design's flexibility and extension.