Trent Boult
Trent Boult

Reputation: 117

Serializable interface in Java

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?

Upvotes: 2

Views: 514

Answers (3)

Branislav Lazic
Branislav Lazic

Reputation: 14816

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.

Upvotes: 0

muasif80
muasif80

Reputation: 6016

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

Upvotes: 1

Henry
Henry

Reputation: 43798

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.

Upvotes: 2

Related Questions