Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do I win when I implement an interface which is blank? [duplicate]

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.

like image 652
Origamer7 Avatar asked Feb 17 '16 08:02

Origamer7


People also ask

What is an empty interface called?

An interface that does not contain methods, fields, and constants is known as marker interface. In other words, an empty interface is known as marker interface or tag interface. It delivers the run-time type information about an object.

What will happen if we are not implementing all the methods of an interface in class which implement an interface?

If a class implements an interface and does not provide method bodies for all functions specified in the interface, then the class must be declared abstract.

How do you use an interface without implementation?

Yes, you can write an interface without any methods. These are known as marking interfaces or, tagging interfaces. A marker interface i.e. it does not contain any methods or fields by implementing these interfaces a class will exhibit a special behavior with respect to the interface implemented.

Do you have to override all interface methods?

On implementation of an interface, you must override all of its methods. Interface methods are by default abstract and public. Interface attributes are by default public , static and final. An interface cannot contain a constructor (as it cannot be used to create objects)


2 Answers

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
    }
like image 88
Suresh Atta Avatar answered Nov 13 '22 06:11

Suresh Atta


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

interface MyInterface1 {}
interface MyInterface2 {}

Consuming code:

if (foo is MyInterface1) ...
like image 45
MakePeaceGreatAgain Avatar answered Nov 13 '22 07:11

MakePeaceGreatAgain