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.
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.
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.
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.
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)
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
}
Those interfaces serve only for differing and identifying instances, consider this:
interface MyInterface1 {}
interface MyInterface2 {}
Consuming code:
if (foo is MyInterface1) ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With