2

I understand that the whole point of having an interface is to force the class that implements it to implement/define all the abstract methods in that interface.

However, in the process of Object Serialization in Java (conversion into byte stream), the class the object to be serialized is an instance of must implement the Serializable interface. However, I see no methods of the interface being defined. So, is that an interface with ZERO methods, if yes, is that even possible and if yes again, what is the purpose if it has no methods?

Trent Boult
  • 117
  • 3
  • Yes, it's the interface without any methods or constants. – PM 77-1 Mar 05 '15 at 21:25
  • Read this for an explanation: http://docs.oracle.com/javase/7/docs/api/java/io/Serializable.html (You may need to do some things if your class requires special handling, and this pages tells you what.) – Michael Welch Mar 05 '15 at 21:26
  • http://stackoverflow.com/questions/20878039/interface-with-no-methods – George G Mar 05 '15 at 21:28

3 Answers3

2

The Serializable interface is a marker interface. If a class implements it, the runtime system knows that the class is serializable.

In modern Java this effect could now be achieved with an annotation but they were not around at the time this interface was defined.

Henry
  • 42,982
  • 7
  • 68
  • 84
1

Yes such an interface is possible. It is called a marker interface. There are other interfaces like this also.

You can have a look at

http://mrbool.com/what-is-marker-interface-in-java/28557

muasif80
  • 5,586
  • 4
  • 32
  • 45
0

As I already stated, purpose of interface with 0 methods is about pure contract. Let me explain it in next example:

Let's say we have a simple data access layer composed of multiple interfaces like:

DeletableDao, InsertableDao, UpdatableDao etc.. and implementation class like DaoImpl:

Let's say we have entity class like this:

public Person implements DaoEntity {
    private int id;
    private String name;

    // getters and setters
}

where DaoEntity is interface with 0 methods because of pure contract:

public DaoEntity {
}

and let's say that our DeletableDao looks like this:

public interface DeletableDao<T extends DaoEntity> {
    void delete(T t);
}

and implementation class:

public DaoImpl implements DeletableDao<Person> {

     public void delete(Person p) {
        // Delete person
    }
}

What this all means? What is a purpose of DaoEntity interface? It means that only instance of DaoEntity subclass can be passed to delete method and deleted.

Branislav Lazic
  • 14,388
  • 8
  • 60
  • 85