Marker Interface doesn't have any method or field or constant declared within it. So a marker interface is an empty interface.
Example :
Now one question that would immediately pop-up in your mind is,
Why would one declare an empty interface?
What good is it of?
In general a common belief is that a marker interface is generally used to send some kind of signal to the JVM and instructs JVM to treat the class implementing it in a special way.
Like, when a class implements Cloneable marker interface, it signals the compiler that the class allows creation of clones of its objects.
Generally, a marker interface is used with the instanceof operator to check if a reference type variable refers to an object whose class implements the marker interface.
You may also like to read about:
Example :
- Serializable,
- Cloneable,
- RandomAccess interface and
- Remote interface
Now one question that would immediately pop-up in your mind is,
Why would one declare an empty interface?
What good is it of?
In general a common belief is that a marker interface is generally used to send some kind of signal to the JVM and instructs JVM to treat the class implementing it in a special way.
Like, when a class implements Cloneable marker interface, it signals the compiler that the class allows creation of clones of its objects.
Generally, a marker interface is used with the instanceof operator to check if a reference type variable refers to an object whose class implements the marker interface.
You may also like to read about:
- Why iterator is fail fast in java?
- Can we call run() directly on thread without calling start?
- Class variable vs instance variable
- iterator vs list iterator
- Why String is immutable in java?
instanceof is used to identify a base type irrespective of whether the interface is a marker or any other special type you may want to call it.
ReplyDeleteThe above interface or the Java specified interfaces are meant to provide a uniform way to interact with the class. If you know how for each loop works you would understand what I mean.
Hi, I am David from https://www.springmockexams.com and https://www.javamockexams.com.
ReplyDeleteI really want to thank you for this post, I am going to share it on all my social media, if you do not mind!
I am also really enthusiast to announce some very exciting news: to celebrate the imminent release of Spring 5 and Java 9 we launched our simulators SALE CAMPAIGN. We halved the price of our simulators at www.springmockexams.com and www.javamockexams.com for limited time only.
If the audience is interested in accessing our price offer, they can take a look here http://www.cm.gy/sme and here http://www.clktr4ck.com/java
Thanks and stay tuned for your featuring on our social medias!
David