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.
Related
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();}
What I understand is that I can implement Serializable interface to make my object serializable.
But I don't get where is writeObject method implemented when Serializable is an interface, so it doesn't contain implementation of methods, just a definition?
As you already noticed, the Serializable is a Marker Interface and does not have any methods to implement. Implementing Serializable is just a note that this one is eligible for serialization which is handled using ObjectOutputStream.
Methods you mentioned need to be implemented in a class implementing the Serializable interface and will be picked up automatically. Since there is no obligation for implementing them, they are not included in the interface.
http://docs.oracle.com/javase/8/docs/platform/serialization/spec/serial-arch.html#a4539
Tough all the answers posted so far are right, I wish to add some extra comments:
java.io.Serializable was already part of the Java 1.1 API (among the first versions of Java), and was meant as an easy way for the programmer to mark any class to have a special behaviour.
According to OOP principles, that should have been done through a regular interface, which is what you (and me, and any other programmer) would have expected. Something like this:
public interface Serializable<E>
{
public E read(DataInput input) throws IOException;
public void write(DataOutput output) throws IOException;
}
But, since there are many classes in Java which needed to be serialized, the Java Language designers wished to save troubles to programmers, by some kind of mechanism through which serialization would be performed automatically. But how?
Through an abstract class? Nope. That would have prevented any custom class to have its own hierarchy (since in Java there is only single inheritance).
Making java.lang.Object serializable? Neither so, because that would have prevented programmers to decide which class should be serializable and which should not.
On top of all, there was a hughe problem: Note that method read is supposed to create and return an object of class E from a DataInput stream. An abstract class just can not create instances of its subclasses whithout further information (the abstract class does not know which is the applied subclass).
So, they decided to pass over the OOP and offer Serialization as a special non-oop feature of the serialization classes ObjectOutputStream/ObjectInputStream (credits to EJP for this detail) in the form of a "dummy" interface recognizable by them, at the price of adding somehow some confussion to the class definitions, because an interface with no methods is nonsense (Same approach they adopted for java.lang.Cloneable).
Actually, it adds even more confussion, because custom serialization must be done by implementing private methods readObject and writeObject (as specified by ObjectOutputStream), which is a feature non describible in terms of a Java interface.
Nowadays, these kind of marking can be done through annotations. Well, think of Serializable as an interface which should have been an annotation, but still remains as an interface for those -endless- compatibility reasons.
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
I am aware of what marker interface is and when we need to use it. One question is still not clear to me. If a marker interface does not have any method or body, how does it work at runtime?
A marker interface doesn't "work" as such. As the name suggests, it just marks a class as being of a particular type. Some other code has to check for the existence of the marker and do something based on that information.
These days annotations often perform the same role that marker interfaces did previously.
The only useful thing you can do with it is
if (instance instanceof MyMarkerInterface) {
...
}
Marker interfaces can be replaced with annotations in many places, however a marker interfaces can still be used for
The compile time checks. You can have a method which must take an object of a class with a given marker interface(s) e.g.
public void myMethod(MyMarkerInterface MMI);
You cannot have this compile time check using an annotation alone.
BTW: You can have two interfaces using generics, but good examples are rare.
Support frameworks which depend on interface(s) to identify a component type. like OSGi.
EDIT: I use this for a Listener marker interface. A listener has methods methods marked with annotations but the methods can have any name or type. It adds a compiler time check to what would otherwise be a purely runtime linking.
public Component implements Listener {
#ListenerCallback
public void onEventOne(EventOne... eventOneBatch) { }
#ListenerCallback
public void onEventTwo(EventTwo eventTwo) { }
}
Marker interface in Java is interfaces with no field or methods or in simple word empty interface in java is called marker interface. e.g. serializable, Clonnable and Remote Interface. They are used to indicate signal or command to the compiler Or JVM. It can also be used to classify code. You can also write your own marker interface and use them to logically divide your code. Also, you can write any pre-processing operation on those class.
A marker interface tells JVM that the class being marked by marker interface to add functionality of a marker interface . Like implementing Cloneable tells JVM that this class implements Cloneable and hence JVM will have to copy it bit-wise.
When there is nothing to implement in the marker interfaces like Serializable What is the use of implementing it?
Joshua Bloch: Effective Java 2nd Edition, p 179
Item 37: Use marker interfaces to define types
...
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....
Personally I think I'll bow to Joshua's superior knowledge on this subject.
In earlier versions of Java, Marker Interfaces were the only way to declare metadata about a class. For example, the Serializable Marker Interface lets the author of a class say that their class will behave correctly when serialized and deserialized.
In modern Java, marker interfaces have no place. They can be completely replaced by Annotations, which allow for a very flexible metadata capability. If you have information about a class, and that information never changes, then annotations are a very useful way to represent it.
It indicates that the class (and consequently all the fields which aren't transient) are candidates for serialisation. And if you're building a framework reliant on serialisation, you can of course write a method thus:
public void registerObject(Serializable obj);
to limit the classes you're prepared to accept.
Because a serialized object needs to retain compatibility across systems, serialisation is an explicit design decision and hence requires the use of the marker interface, to identify such candidates.
There's also a security aspect. You don't want to make everything serialisable - otherwise you can accidentally expose (say) passwords or other sensitive data via serialisation.
Such marker interfaces are useful in the case other code takes decisions depending on whether an object implements some marker interface.
In the case of Serializable, reflection will be used to serialize the fields of the objects.
Now annotations are preferred as they don't propagate to sub-classes.
See Marker interface pattern.
They are called marker interfaces. And as the name implies, they mark that some object is available for certain sort of operations.
Serializable means that the object is eligible for java serialization, for example.
It has been discussed whether they shouldn't be replaced by annotations, since their functions are quite similar.
If you implement an interface then instanceof will be true. If you interface has nothing to implement then you can use this to mark a class with meta-data like annotations do for Java 1.5 and up without having to force the implementor to do anything special.
You are right in reasoning that an empty interface does not affect the "standard" execution of the program which is based on inspection/mutation of fields and dispatching of methods.
However, marker interface are useful when used in conjunction with reflection: A library/method inspects (via reflection) an object and works differently if its class impplements the marker interface. As of Java5 there's very little need for marker interfaces - the same "marking" facility can be achieved via Java annotations - which (again) most of their effect will be achieved via reflection-based code.
Mostly we see use of marker interfaces in scenarios where we want to check if an object of a class has a permission. We check for the permission using the instanceOf.
public interface Herbivorous {
}
public interface Carnivorous {
}
public class Cow implements Herbivorous {
String howMuchGrassConsumed() {
return "2";
};
}
public class Lion implements Carnivorous {
String howManyCowsConsumed() {
return "2";
}
}
public class Jungle{
public static void main(String[] args) {
Cow cow = new Cow();
Lion lion = new Lion();
if(cow instanceof Herbivorous){
System.out.println("Cow ate so much gress:"+cow.howMuchGrassConsumed());
}else if(lion instanceof Carnivorous){
System.out.println("Lion ate so many cows:"+lion.howManyCowsConsumed(););
}else{
System.out.println("That's an alien");
}
}
}
The main purpose is to tell the compiler that treat differently for the object of the class which implemented marker interface.
Looking carefully on marker interface in Java e.g. Serializable, Clonnable and Remote it looks they are used to indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done some special operation on it, similar way if JVM sees one Class is implement Clonnable it performs some operation to support cloning. Same is true for RMI and Remote interface. So in short Marker interface indicate, signal or a command to Compiler or JVM.
Read more: http://javarevisited.blogspot.com/2012/01/what-is-marker-interfaces-in-java-and.html#ixzz2v6fIh1rw