can marker interface like serializable contain default methods?

前端 未结 4 1834
终归单人心
终归单人心 2021-02-14 12:02

I think it can\'t, because marker interface principle is to not have any methods, but since default methods are not abstract I am not sure.

4条回答
  •  眼角桃花
    2021-02-14 12:59

    A marker interface can have default methods, but having them is nonsensical.

    A marker interface differs from a conventional interface in the way it's used. A conventional interface defines methods, both abstract and default. Thus it is sensible for a program to declare variables with that interface as its type, and to call methods of both kinds through a reference of that interface type.

    A marker interface, by constrast, is not used for calling methods. It is a piece of meta-information about an object declared through the type system. It is typically used by calling code via an instanceof expression, or occasionally Class.isAssignableFrom(). It is pointless to declare a variable whose type is a marker interface, since there's nothing you can do with such a variable.

    Examples of marker interfaces in the JDK are Cloneable, RandomAccess, and Serializable.

    Now consider the addition of a default method to some marker interface:

    interface Marker {
        default void foo() { ... }
    }
    

    What could the default implementation of foo do?

    Implementations of default methods typically want to operate on this, and they do so by calling other instance methods on this. They could call other default methods, but having a bunch of default methods calling each other isn't useful. Eventually, some kind of actual operation on this must be performed. Since interface methods have no access to state (fields), any actual operations must be performed by abstract method implementations residing in an implementing class. However, in a marker interface there are no such methods.

    The default implementation of foo could call a static method on this interface or on some other class. This is mostly pointless, as such a method would probably be better expressed as a static method in the first place. The implementation could pass this to a static method, but that method couldn't do anything useful with such a reference, since it has no methods! Well, it might have default methods, but now we're going in circles.

    For a default method to be useful on an interface, that interface needs to have abstract methods as well. But if it has abstract methods, it's no longer a marker interface. Thus, it is nonsensical to have default methods on a marker interface.

提交回复
热议问题