Enum Anatomy

Rule 4:User Marker Interface to define types

Marker Interface has no method ,it is used just to mark a class to be of a type.
Why Use?
Fail-Safe-
Using Interface as type you PREPARE THE CODE NOT TO FAIL AT RUN TIME,it compells you to have code reliability before code goes in running mode.
Contrary: annotaions are also avaiable why not replace maker interface to anootation ? annotation are good to have feature but the Type safety is provided by marker Interface .
Annotations should be used at elemne

for example:
Only those types that are subtype of serializable are allowd to be passed in ObjectOutputStream.writeObject(), any other obect passed will be compelled to be corrected at before code goes to running state .anyways in such a case it will have compile time error.

Question- How does an marker interface(Serializable,Cloneable,Runnable) ensures that only a particular type will be passed to a method(writeObject)?Internal implementation so that it can be modified to oue use case.
Anser: It is taken care by JVM.the marker interface is signal to JVM for a special treatment of Classes implementiong marker Interface.

Note: Checked by JVM means non-reified (runtime) resolution
Compiler compells to do it means compile time check

Counter Question?
can’t we decide special behaviour of a class by a flag.
Ans- Yes, we can but doenot the interface based implementation looks more readable.

simply put: How to ensure type safety with marker interface ..example?
Google Baba –

Published by

Unknown's avatar

sevanand yadav

software engineer working as web developer having specialization in spring MVC with mysql,hibernate

Leave a comment