Marker Interfaces

前端 未结 6 1825
萌比男神i
萌比男神i 2021-01-18 08:42

Could somebody pls explain the contract of marker interfaces in java?

For Ex: If Clonable is a Marker Interface with no fields/methods, then where is t

6条回答
  •  终归单人心
    2021-01-18 08:56

    clone() is defined in the java.lang.Object class which all classes extend from, however it is protected. This is actually a concrete method implementation that does a field by field clone of the object, but only if you've implemented the Cloneable interface to indicate this is allowed.

    In practice many people override the clone() method so that they can make it public and allow cloning from outside the class.

    This whole pattern is quite unusual and not something you would usually replicate, I can't think of many other examples in the JVM where there is a paired marker interface and method. From Java 5 onwards it's better to use annotations for markers. e.g. the @XmlRootElement used to mark a type as Jax-B serializable (post Java 5) vs the Serializable interface (pre Java 5) used to indicate a class is binary serializable.

提交回复
热议问题