The purpose of the interface without defining a method / constant

I am new to Java. I was able to compile the following interface without any errors.

File Name: empty_interface.java

File contents:

 public interface empty_interface {} 

Questions

a) The interface, I believe, is a contract that a developer must implement. What would an implementer implement if it extends the above interface?

b) May be related to a) ... but here I go ... Why did the compiler allow compilation with undefined?

+4
source share
3 answers

There are already several β€œmarker” interfaces in the JDK. It just means that it does not need methods.

The most common example is Serializable, which means that a class can be serialized. The library does the rest, so no additional methods are required.

Unclear is RandomAccess, which means the list can be retrieved randomly in an efficient way. The Collections.sort () function uses it.

Another class is Cloneable, which is a marker interface but probably should have a method

 public Object clone(); 

Since Java 5.0 is better to use meta-information, it is to use annotations, but they were not previously available.

Here is a great Jon Skeet answer to a similar marker interface question in java

+8
source

Empty interfaces are token interfaces that satisfy multiple roles.

Serialization requires an instance of a class that implements Serializable . The only reason the interface exists is to highlight the non-serializable classes (and those that dev doesn't care about serializing for) by the absence, and make the developers of their classes think about whether their class is serializable.

Oddly enough, Serializable mentions several optional methods.

Another hypothetically acceptable, but not very useful use is to accept several unrelated classes without accepting all the specified classes.

+4
source

The interface is not undefined, it simply does not have methods defined for it.

An empty interface usually serves as a flag for whether the class supports any behavior.

Whether this is a good template being discussed, a good example of this in practice is Cloneable and Serializable . Cloneable lets you know that a class implementation can be cloned through Object.clone , and Serializable lets you know that an implementing class allows serialization.

I personally do not see anything wrong with that.

+1
source

Source: https://habr.com/ru/post/1497074/


All Articles