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 ?
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With