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.
Related
Java 8 gave us many fun ways to use functional interfaces and with them a new annotation: #FunctionalInterface. Its job is to tell the compiler to yell at us if we fail to stick to the rules of a functional interface (only one abstract method that needs overriding please).
There are 43 interfaces in the java.util.function package with this annotation. A search of jdk.1.8.0/src for #FunctionalInterface only turns up 57 hits. Why are the other interfaces (such as AutoCloseable) that could have added #FunctionalInterface still missing it?
There is a bit of a vague hint in the annotations documentation:
"An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface"
Is there any good reason NOT to intend that an interface I've designed (that may simply happen to be a functional interface) not be used as one? Is leaving it off an indication of anything besides not realizing it could have been added?
Isn't adding abstract methods to any published interface going to screw anyone implementing it, functional or not? I feel cynical assuming they just didn't bother to hunt them all down but what other explanation is there?
Update: After looking over "Should 'Comparable' be a 'Functional interface'?" I find I still have nagging questions. When a Single Method Interface and a Functional Interface are structurally identical what's left to be different? Is the difference simply the names? Comparable and Comparator are close enough to the same semantically. Turns out they are different structurally though so still not the best example...
Is there a case when an SMI is structurally fine to use as a Functional Interface but still discouraged over the semantic meaning of the name of the interface and the method? Or perhaps the contract implied by the Javadocs?
Well, an annotation documenting an intention would be useless if you assume that there is always that intention given.
You named the example AutoCloseable which is obviously not intended to be implemented as a function as there’s Runnable which is much more convenient for a function with a ()->void signature. It’s intended that a class implementing AutoCloseable manages an external resource which anonymous classes implemented via lambda expression don’t do.
A clearer example is Comparable, an interface not only not intended to be implemented as a lambda expression, it’s impossible to implement it correctly using a lambda expression.
Possible reasons for not marking an interface with #FunctionalInterface by example:
The interface has programming language semantics, e.g. AutoClosable or Iterable (that’s unlikely to happen for your own interfaces)
It’s not expected that the interface has arbitrary implementations and/or is more an identifier than the actual implementation, e.g. java.net.ProtocolFamily, or java.lang.reflect.GenericArrayType (Note that the latter would also inherit a default implementation for getTypeName() being useless for lambda implementations as relying on toString())
The instances of this interface should have an identity, e.g. java.net.ProtocolFamily, java.nio.file.WatchEvent.Modifier, etc. Note that these are typically implemented by an enum
Another example is java.time.chrono.Era which happens to have only a single abstract method but its specification says “Instances of Era may be compared using the == operator.”
The interface is intended to alter the behavior of an operation for which an implementation of the interface without inheriting/implementing anything else makes no sense, e.g. java.rmi.server.Unreferenced
It’s an abstraction of common operations of classes which should have more than just these operations, e.g. java.io.Closeable, java.io.Flushable, java.lang.Readable
The expected inheritance is part of the contract and forbids lambda expression implementations, e.g. in java.awt: ActiveEvent should be implemented by an AWTEvent, PrinterGraphics by a Graphics, the same applies to java.awt.print.PrinterGraphics (hey, two interfaces for exactly the same thing…), wheras javax.print.FlavorException should be implemented by a javax.print.PrintException subclass
I don’t know whether the various event listener interfaces aren’t marked with #FunctionalInterface for symmetry with other multi-method event listener that can’t be functional interfaces, but actually event listeners are good candidates for lambda expressions. If you want remove a listener at a later time, you have to store the instance but that’s not different to, e.g. inner class listener implementations.
The library maintainer has a large codebase with more than 200 candidate types and not the resources to discuss for every interface whether it should be annotated and hence focuses on the primary candidates for being used in a functional context. I’m sure, that, e.g. java.io.ObjectInputValidation, java.lang.reflect.InvocationHandler, juc RejectedExecutionHandler & ThreadFactory wouldn’t be bad as #FunctionalInterface but I have no idea whether, e.g. java.security.spec.ECField makes a good candidate. The more general the library is, the more likely users of the library will be able to answer that question for a particular interface they are interested in but it would be unfair to insist on the library maintainer to answer it for all interfaces.
In this context it makes more sense to see the presence of a #FunctionalInterface as a message that an interface is definitely intended to be usable together with lambda expressions than to treat the absence of the annotation as an indicator for it’s being not intended to be used this way. This is exactly like the compiler handles it, you can implement every single abstract method interface using a lambda expression, but when the annotation is present it will ensure that you can use this interface in this way.
Planned expansion. Just because an interface matches the requirements of an SMI now doesn't mean that expansion isn't needed later.
In java 8, functional interface is an interface having exactly one abstract method called functional method to which the lambda expression’s parameter and return types are matched.
The java.util.function contains general purpose functional interfaces used by JDK and also available for end users. While they are not the complete set of funtional interfaces to which lambda expressions might be applicable, but they provide enough to cover common requirements. You are free to create your own functional interfaces whenever existing set are not enough.
There are many such interfaces available which deserves to be designated as functional interface but java.util.function package already provides functional interfaces for our almost all purposes.
For example look into following code.
public interface Comparable<T> {
public int compareTo(T o);
}
#FunctionalInterface
public interface ToIntFunction<T> {
int applyAsInt(T value);
}
public static void main(String[] args){
ToIntFunction<String> f = str -> Integer.parseInt(str);
Comparable<String> c = str -> Integer.parseInt(str);
}
Comparable can also take an object and derive some int type value but there is a more general dedicated interface ToIntFunction is provided to perform this task. There is no such hard rule that all the deserving interfaces should be annotated with #FunctionalInterface but to gain the advantage of lambda feature, the interface should fulfill all criterias defined by FunctionalInterface.
I've been trying to learn some basic object oriented programming in Java. I was curious to know what the origin of the word interface is , if there is any documented description. Also I was trying to make sense of what it means by thinking of a generic concept as
A point where two systems, subjects, organizations, etc. meet and interact
I got this definition from google search. What are the two systems/entities that are interfacing? Or maybe my analogy used is inappropriate?. So far I think of it as a skeleton to define methods and property outlines.
Software interfaces are one-way (though there are ways to pass the calling object as a reference to the callee), unlike Electrical connectors that interface both ways directly.
If you accept that difference in definition then the object 'implementing' the interface, is the object to be interfaced with. it allows other objects to connect to it using a well defined set of methods.
To compare it further to electronics, if 3 different types of devices all support audio-jacks, then all 3 devices essentially state: you can listen to me, I play audio. They could be very different devices (mp3 player, sonar, geiger counter) but they all clearly state: if you plug in a headphone, you can get sound out of me.
This is what an interface does in software. it states: I provide feature X, no matter what actual component I am.
so anything that implements the Map interface, can have .get(...) and .values() and .keySet() called on it. Anything that implements an AudioStream interface will yield an audiostream when called.
The object interfacing with the object supplying the interface can interact with this object in a predefined and well documented way. Ofcourse, how the object providing the interface actually makes it work can be completely different.
An interface defines the common interface (hence the name :) multiple objects (of potentially different types) have in terms of method signatures. This is for consumption by other objects.
The JLS Chapter 9 states:
An interface declaration introduces a new reference type whose members
are classes, interfaces, constants, and methods. This type has no
instance variables, and typically declares one or more abstract
methods; otherwise unrelated classes can implement the interface by
providing implementations for its abstract methods. Interfaces may not
be directly instantiated.
So this is more of a definition in terms of behavior than etymology.
The interface links your code (i.e. the class that implements your interface), and outside code. The outside code has access to your interface, but need not know your implementation.
The "two systems" (you asked for) are then the code implementing an interface and the code referencing it.
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().
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
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