Reputation: 3321
I am a newbie to Java. I was able to compile the following interface without any errors.
File Name : empty_interface.java
File content :
public interface empty_interface {}
Questions
a) Interface , i believe, is a contract which the implementor has to implement. What would a implementor will implement if it extends the above interface ?
b) Might be related to a)...but here I go...Why would compiler allow a undefined interface to compile successfully ?
Upvotes: 4
Views: 364
Reputation: 11006
The interface isn't undefined, it just has no methods defined for it.
An empty interface typically serves as a flag for whether a class supports some behavior.
Whether this is a good pattern is debated, a good example of this in practice is Cloneable, and Serializable. Cloneable lets you know the class implementing it can be cloned via Object.clone
, while Serializable lets you know the implementing class allows serialization.
I personally see nothing wrong with this.
Upvotes: 1
Reputation: 533880
There are a number of "marker" interfaces in the JDK already. This just signify something which doesn't need methods.
The most common example is Serializable which signifies the class can be serialized. The library does the rest so no additional methods are required.
An obscure one is RandomAccess which signifies than a List can be accessed randomly in an efficient manner. The Collections.sort() uses it.
Another class is Cloneable which is a marker interface but probably should have had a method
public Object clone();
Since Java 5.0, a better way to add meta information like this is to use Annotations, but these were not available previously.
Here is Jon Skeet's excellent answer to a similar question marker interface in java
Upvotes: 8
Reputation: 41311
Empty interfaces are marker interfaces, that satisfy multiple roles.
Serialization requires an instance of a class that implements Serializable
. The only reason the interface exists is to mark out non-serializable classes(and those the dev doesn't care about serialization for) by absence, and to make developers of their own classes think as to whether their class is serializable.
Oddly enough Serializable
mentions a couple of optional methods.
Another hypothetically-valid but not very-useful use is to accept multiple unrelated classes without accepting all said classes.
Upvotes: 4