61

When there is nothing to implement in the marker interfaces like Serializable What is the use of implementing it?

Kushal
  • 8,100
  • 9
  • 63
  • 82
GuruKulki
  • 25,776
  • 50
  • 140
  • 201

10 Answers10

95

Joshua Bloch: Effective Java 2nd Edition, p 179

Item 37: Use marker interfaces to define types

... You may hear it said that marker annotations (Item 35) make marker interfaces obsolete. This assertion is incorrect. Marker interfaces have two advantages over marker annotations. First and foremost, marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. The existence of this type allows you to catch errors at compile time that you couldn’t catch until runtime if you used a marker annotation....

Personally I think I'll bow to Joshua's superior knowledge on this subject.

T C
  • 1,101
  • 7
  • 4
  • 1
    The problem is, this often contradicts Item 19: Use interfaces only to define types. "Serializable" is not a type, it's a property/behaviour. – Tom B Mar 01 '15 at 14:04
  • 6
    Actually, even "Serializable" can be seen as a type. Consider the following method signature: public void serialize(Serializable objectToSerialize); In this case, it is clear at compile time that only serializable objects can be passed to "serialize", this isn't possible with annotations. – Mirko Klemm May 11 '15 at 08:42
67

In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.

In modern Java, marker interfaces have no place. They can be completely replaced by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.

Nikola Yovchev
  • 9,498
  • 4
  • 46
  • 72
Chris Pitman
  • 12,990
  • 3
  • 41
  • 56
  • 20
    I really like annotations but in this case they have the drawback of being a bit more complicated to check for (compared to using instanceof). They are also not as well integrated in javadoc (where a quick way to see what implements or not is to just look it up and see the list of implementing classes). So I would say they still have a place, just not an equally important one. – Fredrik Jan 04 '10 at 14:20
  • 12
    @Chris so are you right or is Josh Bloch right here? http://stackoverflow.com/a/5080547/632951 – Pacerier Mar 07 '12 at 16:27
  • 1
    @Pacerier I would argue that since marker interfaces define no behavior, they are essentially meaningless for type safety. Just because a class is marked serializable does not mean it can be correctly serialized, and missing the marker interface doesn't imply serialization would not work. It can just mean that the developer messed up marking it! If the interface actually had methods (and was no longer a marker), then it would enforce a behavior contract. It is also much more work to include additional metadata with a marker interface, while with annotations it is part of the point. – Chris Pitman Jun 14 '12 at 21:33
  • 9
    Think of hibernate which has a method: Session.get(Serializable id). With a marker interface, you can specify that the identifier has to be Serializable. If we were to use an annotation instead, you could no longer be able to get a compile time error if you did something like this: session.get(new Object()). Instead we'd have to check for the annotation at runtime and issue an exception. – Matt Jun 27 '12 at 17:35
  • 1
    @Matt Sure, I understand the use case. But unline a true interface, simply implementing Serializable doesn't actually enforce any compile time contract. For example, a type could have been serializable at one point, marked as such, and then modified to no longer be truly serializable without the interface being removed. "Type Safety" isn't buying much of anything in this case. – Chris Pitman Jun 28 '12 at 03:51
  • 1
    @ChrisPitman `You may hear it said that marker annotations (Item 35) make marker interfaces obsolete.` **This assertion is incorrect.** `Marker interfaces have two advantages over marker annotations. First and foremost, marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not.` -Bloch Effective Java 2nd Edition – Kevin Meredith Dec 05 '13 at 22:09
  • @KevinMeredith If you look below you'll see that this exact same quote has already been posted. I am not unaware of Joshua Bloch's assertion. However, as I said above, an interface with no behavior (ie a marker interface) provides nearly no type safety. Saying that a type "implements" a marker interface is nearly an empty assertion. A type that implements `Serializable` can easily *not be serializable*, which goes against the entire point of an interface. – Chris Pitman Dec 05 '13 at 22:44
  • 2
    BTW Marker interfaces cannot be completely replaced by annotations as you can ensure an arguments has a marker interface, but not an annotation e.g. `writeObject(Serializable s)` This check for the marker interface cannot be replaced with an annotation. – Peter Lawrey May 07 '14 at 12:34
  • 2
    According to this logic ("an interface with no behavior provides nearly no type safety"), the `Set` interface shouldn't exist as well. It doesn't provide any additional methods over `Collection`, only specifies the contract. – Malcolm Sep 15 '14 at 17:27
  • if it's for metadata. why not to use comment // over Marker interface or annotation? I'll simply put a comment on a top of class that class is Serialized or a method is overridden? – Govinda Sakhare Mar 30 '15 at 07:06
  • 1
    @govi Because the point is to have metadata that can be accessed at runtime by your application. You cannot get comments from a type via reflection, so they really are not relevant. – Chris Pitman Mar 30 '15 at 17:19
  • so you mean metadata is for JVM , not for programmer .right? – Govinda Sakhare Mar 31 '15 at 04:48
  • It's very misleading. Just check Joshua answer below www.stackoverflow.com/a/5080547/632951 – RATHI May 08 '18 at 21:41
  • @Malcolm That statement does not assert that. If you have an implementation of the `Set` interface and you remove the public facing implementation of any member defined in the `Collection` interface and inherited by the `Set` interface, you will get a compile time warning because your implementation now no longer implements the `Set` interface. Do you have a guarantee that an implementation of the `Set` interface properly implements a set? No, but implementing an interface has no guarantee of correctness. – MichaelCook Nov 09 '21 at 01:18
  • @MichaelCook I don't really see your point. Are you saying that `Set` isn't the same as a marker interface or that it shouldn't exist indeed? – Malcolm Nov 09 '21 at 08:47
  • @Malcolm I suppose what I'm getting at is that `Set` is not a marker interface, nor is it an empty interface. It defines behavior; however, it just so happens that all of the behavior that it defines is inherited from the `Collection` interface. If I say a class implements `Set` there are method I *need* to implement for that to be true. That is not the case with `Serializable`. I can take a class that is not serializable, say it implements the `Serializable` interface and there is nothing I need to implement to ensure that is true. – MichaelCook Nov 09 '21 at 22:16
  • @MichaelCook The main principle is the same: a marker interface doesn't introduce any new methods over nothing just as `Set` doesn't over `Collection`. Instead both introduce a new type and specify a certain contract it is supposed to adhere. Just implementing methods defined in `Set` doesn't make it a `Set` yet even if it's a proper `Collection`. It just satisfies the compiler, but doesn't make it a correct program. – Malcolm Nov 10 '21 at 09:02
  • @Malcolm Correctness of implementation is a moot point. The java compiler, nor any compiler for that matter, can verify correctness of implementation. Interfaces enforce that behavior exists; however, it does not, and can't, enforce correctness. There's nothing on the `Collection` interface that forces me to implement the `Add` method such that it persists the given item in some data structure as you would expect an implementation of the `Collection` interface to do. – MichaelCook Nov 10 '21 at 20:05
  • @MichaelCook Yes, exactly, the compiler doesn't verify the correctness of the program. So why does `Set` exist if it's the same as `Collection`? Why not just use `Collection`? – Malcolm Nov 11 '21 at 09:03
5

It indicates that the class (and consequently all the fields which aren't transient) are candidates for serialisation. And if you're building a framework reliant on serialisation, you can of course write a method thus:

public void registerObject(Serializable obj);

to limit the classes you're prepared to accept.

Because a serialized object needs to retain compatibility across systems, serialisation is an explicit design decision and hence requires the use of the marker interface, to identify such candidates.

There's also a security aspect. You don't want to make everything serialisable - otherwise you can accidentally expose (say) passwords or other sensitive data via serialisation.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
5

Such marker interfaces are useful in the case other code takes decisions depending on whether an object implements some marker interface.

In the case of Serializable, reflection will be used to serialize the fields of the objects.

Now annotations are preferred as they don't propagate to sub-classes.

See Marker interface pattern.

Gregory Pakosz
  • 69,011
  • 20
  • 139
  • 164
5

They are called marker interfaces. And as the name implies, they mark that some object is available for certain sort of operations.

Serializable means that the object is eligible for java serialization, for example.

It has been discussed whether they shouldn't be replaced by annotations, since their functions are quite similar.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
3

If you implement an interface then instanceof will be true. If you interface has nothing to implement then you can use this to mark a class with meta-data like annotations do for Java 1.5 and up without having to force the implementor to do anything special.

cyborg
  • 5,638
  • 1
  • 19
  • 25
1

You are right in reasoning that an empty interface does not affect the "standard" execution of the program which is based on inspection/mutation of fields and dispatching of methods.

However, marker interface are useful when used in conjunction with reflection: A library/method inspects (via reflection) an object and works differently if its class impplements the marker interface. As of Java5 there's very little need for marker interfaces - the same "marking" facility can be achieved via Java annotations - which (again) most of their effect will be achieved via reflection-based code.

Itay Maman
  • 30,277
  • 10
  • 88
  • 118
0

Mostly we see use of marker interfaces in scenarios where we want to check if an object of a class has a permission. We check for the permission using the instanceOf.

public interface Herbivorous {
}
public interface Carnivorous {
}
public class Cow implements Herbivorous {
    String howMuchGrassConsumed() {
        return "2";
    };
}
public class Lion implements Carnivorous {
    String howManyCowsConsumed() {
        return "2";
    }
}
public class Jungle{
    public static void main(String[] args) {
        Cow cow = new Cow();
        Lion lion = new Lion();
        if(cow instanceof Herbivorous){
            System.out.println("Cow ate so much gress:"+cow.howMuchGrassConsumed());
        }else if(lion instanceof Carnivorous){
            System.out.println("Lion ate so many cows:"+lion.howManyCowsConsumed(););
        }else{
            System.out.println("That's an alien");
        }
    }
}
-2

The main purpose is to tell the compiler that treat differently for the object of the class which implemented marker interface.

Chanikag
  • 1,419
  • 2
  • 18
  • 31
  • 2
    This is plain wrong. The Java compiler or JVM does nothing special for Serializable and other marker interfaces, but the java library classes consuming it need to recognize Serializable objects and they may consider it and process such objects differently, but not the compiler or JVM. This is a common misconception about the Marker interfaces. – Saurabh Patil Jan 17 '15 at 08:35
-2

Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.

Read more: http://javarevisited.blogspot.com/2012/01/what-is-marker-interfaces-in-java-and.html#ixzz2v6fIh1rw

  • 2
    This is plain wrong. The Java compiler or JVM does nothing special for Serializable and other marker interfaces, but the java library classes consuming it need to recognize Serializable objects and they may consider it and process such objects differently, but not the compiler or JVM. This is a common misconception about the Marker interfaces. – Saurabh Patil Jan 17 '15 at 08:08