Marker Interfaces in Java - java

Is there a list of standard marker interfaces in Java? I've read (in some Java book) that marker interfaces do not have any methods to implement , however when I did a google search - there are certain answers which specify that marker interfaces can indeed have methods. If that is the case then I think there is no difference between a regular interface and marker interface - would it be possible to clear my confusion :)

There is indeed no technical difference between "standard" and "marker" interfaces.
Normally you define an interface to define methods that implementing classes should have. If you don't specify any methods you call the interface a marker interface, since if only marks the class as having some property.
Examples of that are Serializable, Cloneable etc. Those interfaces don't define any methods themselves, but by convention and specification you have to option to implement some special methods related to them, e.g. some serializaton methods related to Serializable. The core Java libraries would then use reflection to check whether those methods exist if a marker interface is implemented.

There is at least one: Serializable. I personally do not remember others.
The technique of defining ta interfaces is old and almost obsolete since java 1.5 when annotations were introduced, so you can use annotation to "tag" class instead of empty interface.

Marker interfaces are used as a tag to inform a message to the java compiler so that it can add special behaviour to the class implementing it and they do not have any method declarations.
The need for marker interface no longer exists since the introduction of the java annotation feature.
Better use the more powerful java annotations than the marker interface.
Some examples of marker interfaces:
java.lang.Cloneable
java.io.Serializable
java.rmi.Remote
java.util.EventListener

SigleThreadModel is also marker interface - ( I know it's deprecated now, but just for example I'm putting it's name here)
See more about it here

An interface is called a marker interface when it is provided as a handle by Java interpreter to mark a class so that it can provide special behaviour to it at runtime and they do not have any method declarations
Java Marker Interface Examples
java.lang.Cloneable
java.io.Serializable
java.util.EventListener

I don't know that there is a list of marker interfaces in the standard Java api. Whether marker interfaces can specify methods is explained well, I think, in the Wikipedia article "Marker interface pattern". Here's an excerpt that addresses your question directly:
Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used.
Aside from the Serializable interface mentioned in the article, there are few others. The only one I can remember off the top of my head is javax.security.auth.callback.
Just thought of another one: javax.security.auth.login.Configuration.Parameters. I'm pretty sure there are more.

Marker interfaces in Java SE 8:
Most widely used:
java.lang.Cloneable
java.io.Serializable
java.util.RandomAccess
java.util.EventListener
Remark: EventListener is officially known as 'tagging interface'.
Others:
java.util.concurrent.CompletableFuture.AsynchronousCompletionTask
java.sql.ParameterMetaData
javax.xml.stream.events.EndDocument
javax.management.loading.PrivateClassLoader
java.security.KeyStore.Entry
java.security.KeyStore.LoadStoreParameter
java.security.KeyStore.ProtectionParameter
java.security.Policy.Parameters
javax.security.auth.callback.Callback
javax.security.auth.login.Configuration.Parameters

Related

Marker interface vs empty abstract class

I am facing difficulties to decide between using a marker interface or an empty abstract class.
I have two classes BrokerResponse and Notification, which have no structural similarity. The only thing connecting them is the need to be subscribable for.
void register(Receivable receivable, BrokerObserver observer)
I somehow dislike using a Marker Interface, because it violates the basic definition of an Interface. On the other hand using an abstract super class would make me as uncomfortable, because both classes have no relationship with one another.
What is the generally preferable approach in this scenario and why?
Edit 1
I forgot to mention, that BrokerResponse is an abstract class itself, that has several subclasses to determine the respective type.
Abstract class vs. marker interface:
There is nothing wrong with marker interface and there are some use cases for it. Choosing between those two, marker interface has more flexibility.
If you do want to define a type, do use an interface.
An abstract class’s purpose is to provide an appropriate superclass from which other classes can inherit and thus share a common design - your classes don't have common design and nothing to share. Moreover you will stick both of them to some restricted design and will be not so flexible if you will need to add a real different parents to them in the future.
List of use-cases for abstract class:
Share code among several closely related classes.
Classes that extend your abstract class have many common methods or
fields or require access modifiers other than public (such as
protected and private).
Declare non-static or non-final fields what enables you to define
methods that can access and modify the state of the object to which
they belong.
Use-cases for interface:
Unrelated classes would implement your interface.
Specify the behavior of a particular data type, without concerning
who implements its behavior.
Advantage of multiple inheritances.
All listed arguments are for the usage of interface. Since BrokerResponse is abstract itself and has it's own hierarchy, making the fact that those classes don't have something in common more stronger.
As alternative you can use marker annotation. I would consider to stick one of those two approaches instead of Abstract Class.
Marker interface vs. marker annotation:
According to Joshua Bloch's 'Effective java':
Marker interfaces have two advantages over marker annotations. First
and foremost, marker interfaces define a type that is implemented by
instances of the marked class; marker annotations do not. The
existence of this type allows you to catch errors at compile time that
you couldn’t catch until runtime if you used a marker annotation.
Another advantage of marker interfaces over marker annotations is that
they can be targeted more precisely.
When should you use a marker annotation?
you must use an annotation if the marker applies to any program
element other than a class or interface, as only classes and
interfaces can be made to implement or extend an interface.
When should you use a marker interface?
Ask yourself the question, Might I want to write one or more methods
that accept only objects that have this marking? If so, you should use
a marker interface in preference to an annotation. This will make it possible
for you to use the interface as a parameter type for the methods in
question, which will result in the very real benefit of compile-time
type checking.
Summary:
If you want to define a type that does not have any new methods
associated with it, a marker interface is the way to go.
If you want to mark program elements other than classes and
interfaces, to allow for the possibility of adding more information to
the marker in the future, or to fit the marker into a framework that
already makes heavy use of annotation types, then a marker annotation
is the correct choice.
Using empty abstract class does not make any sense in this case as there is no multiple inheritance in Java.
Making you class implement some marker interface does not change you class hierarchy, it just marks your class with some additional metadata.
Image the case when your class which already is marked as Subscribable should also be for example Writable. If you use empty abstract class you will need to redesign the entire hierarchy. With marker interface it is just as easy as to add Writable to list of implementations.
How about annotating them? You got your answer that using a mark interface is the way to go here if you would have to choose, but using an annotation depending on what you might need to do would be much cleaner.
The fact that you say you need to make them somehow "the same" talks about an instanceof call and doing something based on that. The same thing could be achieved via isAnnotationPresent or the like.
But if you add a marker interface, how about making it not a marker interface - only in case you have a finite number of classes you need to test against? Something along the lines of MyInterface {boolean isSubscribable();}

Java: Mixin implementation classes

I've seen in several code libraries classes named Mixin with comments like:
//Mixin style implementation
public class DetachableMixin implements Detachable {}
Which is the concept under this style of implementations?
Here is a qoute from Joshua Bloch "Efective Java" (I don't think, I could explain it better myself):
Interfaces are ideal for defining mixins. Loosely speaking, a mixin is a type
that a class can implement in addition to its “primary type” to declare that it provides
some optional behavior. For example, Comparable is a mixin interface that
allows a class to declare that its instances are ordered with respect to other mutually
comparable objects. Such an interface is called a mixin because it allows the
optional functionality to be “mixed in” to the type’s primary functionality.
Abstract classes can’t be used to define mixins for the same reason that they can’t
be retrofitted onto existing classes: a class cannot have more than one parent, and
there is no reasonable place in the class hierarchy to insert a mixin.
The other answer is spot on, but it might be worth pointing out that other JVM languages go even further.
Scala for examples has traits - basically "interfaces" with method implementations. In scala, you can mix one class together with multiple traits, thereby allowing to inherit behavior from several different "places.
Basically the same concept that Java picked up with Java 8, where you know can add default method behavior to interfaces. And for the record: if I recall it correctly, Java8 interfaces and default methods are not meant to introduce a full "mixin" concept in the Java language. The idea is not that you should use this feature to achieve multiple inheritance through the back door. See this lengthy answer from Stuart Mark, one of the people driving the Java language evolution. They state:
The purpose of default methods ... is to enable interfaces to be evolved in a compatible manner after their initial publication.
A good article about implementing mixin pattern with Virtual Extension Methods since Java 8: https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/
The virtual extension method is something new in Java. It brings another mean of expression to create new patterns and best pratices. This article provides an example of such a pattern, enabled in Java 8 due to the use of virtual extension methods. I am sure you can extract other new patterns from them. But, as I have experienced here, you should not hesitate to share them in a view to check their validaty.

Different term used to mention an Interfaces special properties in java?

I am working in java from some time. I know their are some thing knows as interface in java. While reading about them I come to know their is marker interface. Recently when i started reading about java 8 I come to know about an other interface Functional Interface.
I am just wondering what are the different kind of Interfaces available in java?
The Java language specification doesn't itself define the term marker interface and the term has been coined by authors, developers and designers. One common question asked is if we can create a marker interface or not and the answer is yes because of following reason:
We can't create marker interface similar to Serializable or Cloneable but we can simulate the functionality by writing extra code around the custom marker interface.
An empty interface is known as tag or marker interface. For example Serializable, EventListener, Remote(java.rmi.Remote) are tag interfaces. These interfaces do not have any field and methods in it.
Read more here: http://beginnersbook.com/2016/03/tag-or-marker-interfaces-in-java/
Functional Interface is the new addition in Java 8, An interface with exactly one abstract method is called Functional Interface. Read more here.
There are no other types of Interfaces in Java.
There's no special meaning for each.
Marker interface is kind of "design pattern", you attach a label/tag to a set of objects in order to indicates that they have something in common, they're OK for some kind of process or operations. Serializable is a typical example, it marks objects that they can be serialized/deserialized.
On the other hand for FunctionalInterface, it's just an interface with restriction that can only have one abstract method, and thus represents a single function contract. Java 8 add lambda expression for functional programming, for FP we need to pass function back and forth so often. Say we have an interface like:
public interface StringTrasformer {
String transform(Object obj);
}
Traditionally we can only create instance of asynchronous class like:
someObj.doTransform(new StringTransformer() {
#Override
public String transform(Object object) {
return "result";
}
});
But there's only one method to be implemented, so it's no need to make code so verbose, with lambda expression it could be as short as:
abc.doTransform(object -> "result");
Annotation FunctionalInterface is used for compiler to check whether the interface you have annotated is a valid one. Even functional interface is for lambda expressions, method referencesand constructor references, but nothing prevents you to use it the traditional way. Because essentially it is just an normal interface.

What is the internal implementation of marker interface?

I know something about 'marker interface', a marker interface doesn't have any members. For example: Serialiazable, Cloneable etc.
I found in googling that the marker interface is for sending some instructions to JVM? I want to know what are those instructions and how I could understand? Please help me with a real world example.
A marker interface is a means of marking that a class is or does some things and even those things are not expressed as actual methods. For example Serialiazable,Cloneable etc. And since annotations are introduced they are almost always preferred though they cannot replace completely Marker Interface, as suggested by Joshua Bloch
... You may hear it said that marker annotations (Item 35) make marker
interfaces obsolete. This assertion is incorrect. Marker interfaces
have two advantages over marker annotations. First and foremost,
marker interfaces define a type that is implemented by instances of
the marked class; marker annotations do not. The existence of this
type allows you to catch errors at compile time that you couldn’t
catch until runtime if you used a marker annotation....
In case of Serializable, a class implements this interface to indicate that its non-transient data members can be written to an ObjectOutputStream. Also a serialized object needs to retain compatibility across systems and it is an explicit design decision and hence requires the use of the marker interface, to identify such candidates.
Similarly implementing Cloneable tells JVM that this class implements Cloneable and hence JVM will have to copy it bit-wise.
found in googling that the marker interface is for sending some instructions to JVM?
No. They are used as a marker to other Java code.
I want to know what are those instructions
It is nothing more exotic that an instanceof test.
A marker interface doesn't have an implementation.
However, a marker interface will typically influence the behaviour some other classes.
I found in googling that the marker interface is for sending some instructions to JVM?
That is incorrect.
What it is doing is providing information to either the JVM or to classes either provided by or running on the JVM. The information is NOT in the form of "instructions". Rather it is a label at the class level.
For example, when you declare a class as Serializable, you are passing information to the ObjectInputStream and ObjectOutputStream that instances of that class can be serialized. You are passing that information in the form of the class itself; i.e. ObjectInputStream and ObjectOutputStream can use instanceof (or equivalent) to test if an object is serializable.
Please help me with a real world example.
Serializable and Cloneable are the well-known examples in the Java class libraries.
There are other interfaces which have an "marker-interface-like" aspect. For example Closeable and Autocloseable both have a single close() method that does the same thing. The difference is that AutoCloseable is treated as a marker by a "try with resources" statement.
Finally, it is worth nothing that marker interfaces are frowned on by OO design purists. You can achieve the same end using Java annotations.

How is the Comparable interface is marker interface, with its compareTo() method?

How is the Comparable interface is marker interface, even though it defines a compareTo() method?
Please explain detail.
A marker interface is just a design pattern. So even if you read around "X is a marker interface" this doesn't really mean anything apart from "X is an interface with no methods declared".
Since Comparable<T> has one method then it is not used as a marker interface.
A marker interface is useful when you want to attach data to a type to be able to use this data in specific situations, this is not the case of Comparable, which is used to provide an effective interface.
I don't even think that the definition of marker interface is used in javadoc to describe empty intefaces such as Serializable (not sure about it though).
It is not a marker interface. Marker interface in Java for e.g. Serializable, Clonnable and Remote are used to indicate something to compiler or JVM; indicate a flag to compiler.
Quoting Wikipedia on Marker interface pattern (emphasis mine):
[...] class implements a marker interface, and methods that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies functionality (in the form of method declarations) that an implementing class must support, a marker interface need not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. Hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used.
That being said Comparable<T> can be called a marker interface, but it's confusing and I've never heard this before.
I can't imagine a class testing whether some object implements Comparable<T> without actually down-casting and calling compareTo().

Categories