7

I have a question regarding "Interfaces" in Java and the question sounds like this:

What is the use of implementing a blank (empty) interface in my class?

In order to get a better understanding of the question, I will give you a concrete example:

If you go and see the implementation of "ArrayList" class, you will find out that it implements two interfaces (RandomAccess and Cloneable), which are actually totally empty!

Why is that happening? What do I win by implementing a totally blank interface for my class?

In case you have any ideas, please leave a comment.

Thank you in advance.

Zippy
  • 1,804
  • 5
  • 27
  • 36
Origamer7
  • 315
  • 3
  • 17

2 Answers2

6

Those interfaces are called as Marker interfaces (used to mark the class of that type) and at run time they are used to check the type.

For ex

While running the programm, internal logic may goes like

if (yourList instanceof Cloneable) {
        // Hey this object is of type Clonable, please proceed 
    } else {
        // Not that type. Reject
    }
Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 2
    `ObjectOutputStream` has this kind of check for `Serializable` (marker interface) +1 – TheLostMind Feb 17 '16 at 09:04
  • @SURESHATTA: Thank you very much for your answer. I have never heard the term "Marker Interface" and that was actually the key. I was a great help. – Origamer7 Feb 17 '16 at 09:24
1

Those interfaces serve only for differing and identifying instances, consider this:

interface MyInterface1 {}
interface MyInterface2 {}

Consuming code:

if (foo is MyInterface1) ...
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111