Why not multiple abstract methods in Functional Interface in Java8? [duplicate] - java

This question already has answers here:
Why Functional Interfaces in Java 8 have one Abstract Method?
(4 answers)
Closed 5 years ago.
#FunctionalInterface
interface MyLambda {
void apply1();
int apply2(int x, int y);
}
Now using the Lambda expressions why can't Java allow below two as it clearly differentiate between the two:
MyLambda ml1 = () -> System.out.println("Hello");
MyLambda ml2 = (x, y) -> x+y;

The answer would be that in order to create a valid implementation, you would need to be able to pass N lambdas at once and this would introduce a lot of ambiguity and a huge decrease in readability.
The other thing is that #FunctionalInterface is used to denote an interface which can be used as a target for a lambda expression and lambda is a SINGLE function.
Anyway, your example is not valid and would not compile because it tries to create two incomplete implementations on the functional interface.

Writing Lamba expression meaning we are implementing the interface that is functional interface. It should have one abstract method because at the time of lambda expression, we can provide only one implementation at once.
So in the code snippet posted in the question, at any time we are giving only one implementation while declaring Lambda where we will have to implement for two abstract methods.
Thanks for the help.

A functional interface is an interface that has just one abstract
method (aside from the methods of Object), and thus represents a
single function contract. This "single" method may take the form of
multiple abstract methods with override-equivalent signatures
inherited from superinterfaces; in this case, the inherited methods
logically represent a single method.
https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.8

Related

Is the purpose of `abstract` keyword in a FunctionalInterface to distinguish the 'lambda' method from other abstract methods? [duplicate]

This question already has answers here:
Are all methods of interface abstract?
(7 answers)
Why Functional Interfaces in Java 8 have one Abstract Method?
(4 answers)
what is a abstract method on a interface in java [duplicate]
(4 answers)
When we add two abstract methods in an interface and implement just one method then why can't we implement the other method using lambda?
(1 answer)
Closed 1 year ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Duplicate This question has been answered, is not unique, and doesn’t differentiate itself from another question.
Is the purpose of abstract keyword in a FunctionalInterface to distinguish the 'lambda' method from other abstract methods?
Since methods that have no body in an interface are abstract, and Functional Interfaces that have only one method do not have the abstract keyword, I was wondering whether the real purpose of the abstract keyword is to mark or distinguish which among the 'abstract' methods in a Functional Interface will serve as the 'carrier' of the lambda expression.
Is my understanding correct?
This method does not have the abstract keyword but is a functional interface:
public interface AllTrades {
public boolean checkSalary(ATrade t);
}
now suppose the interface above had 2 methods, they are both abstract,
but the interface is no longer a FunctionalInterface
public interface AllTrades {
public boolean checkSalary(ATrade t);
public boolean checkSalary2(ATrade t);
}
Now if we mark which method is abstract, it is a Functional Interface again:
public interface AllTrades {
abstract public boolean checkSalary(ATrade t);
public boolean checkSalary2(ATrade t);
}
Is my understanding correct?
Although you can use abstract in an interface, it has no extra meaning, as all methods in an interface (except default, private or static methods) are by definition abstract. It has no extra meaning in a functional interface, and if you annotate your interface with #FunctionalInterface, both of your examples with two methods will fail to compile as they are equivalent.
To be complete, your first example does have an abstract method, and is a potential function interface. Your second and third example both have two abstract methods, and cannot be used as a function interface.
See also the Java Language Specification 17, section 9.4:
An interface method lacking a private, default, or static
modifier is implicitly abstract. Its body is represented by a
semicolon, not a block. It is permitted, but discouraged as a matter
of style, to redundantly specify the abstract modifier for such a
method declaration.
(emphasis mine)
and section 9.8:
A functional interface is an interface that is not declared sealed
and has just one abstract method (aside from the methods of
Object), and thus represents a single function contract.
All methods in interfaces are public and abstract by default, and the inclusion of either of those modifiers does not change the behavior of the code in any way. You can verify this by compiling the second and third code samples with the #FunctionalInterface annotation, which would result in a compile time error.
Edit:
From the Java Language Specification
9.8. Functional Interfaces
9.4.3. Interface Method Body
9.6.4.9. #FunctionalInterface

Functional Interface vs Interfaces with single methods like Runnable [duplicate]

This question already has answers here:
What are functional interfaces used for in Java 8?
(11 answers)
Closed 4 years ago.
While going through Functional Interfaces, I am not able to understand how are they different from other interfaces with a single method, like Runnable.
We can use Runnable as we try to use other Functional interfaces.
Prior to Java 8, we already could create interfaces and anonymous objects for a single piece of functionality.
For example:
#FunctionalInterface
public interface ITrade {
public boolean check(Trade t);
}
How is this different from:
public interface ITrade {
public boolean check(Trade t);
}
There is no difference, the docs for FunctionalInterface state:
An informative annotation type used to indicate that an interface type declaration is intended to be a functional interface [emphasis added]
and
However, the compiler will treat any interface meeting the definition of a functional interface as a functional interface regardless of whether or not a FunctionalInterface annotation is present on the interface declaration.
So the annotation is only there to indicate that the developer intended the interface to be used as a functional interface.

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.

Does Java 8 support functions as first class objects?

I've read today about the Java 8 release. But I don't understand fully the concept of reference methods in Java 8. Does this mean that Java now has the support of functions as first class objects? I have seen, how to construct a reference to function. But it seems to me, that the Converter object they provide has quite limited functionality. Is it now possible in Java:
to pass the function as the argument to another function?
to return the function as the return value from another function?
and what about closures? Are they implemented fully like in functional languages, or they do have some limitations? It seems to me that there are some limitations (you cannot change the value of the variable you reference in a closure, it must be marked as final and etc).
The most important aspects of first-class functions have been blended into the existing Java type system. No true function type has been introduced; any single-method interface is its own "function type". So, as for your first two questions, you can freely pass around instances of such functional interfaces.
There are many subtle changes to the semantics, which allow one to use lambda syntax/method references to implement any such interface. You can even use higher-order functions such as compose, which returns a generic Function type, and pass it to a method which expects a compatible functional interface type.
you cannot change the value of the variable you reference in a closure
This is not a limitation specific to Java. In fact, most FP languages don't support mutable variables of any kind. Note that there is no requirement to use the final keyword on the variable; the concept of effectively final takes care of that.
It is possible. How do you do it?
First construct a "Functional Interface" (or use one of the provided ones). A functional interface is an interface with a single method. java.lang.Runnable is an example.
Second, write a method that takes a functional interface as a parameter.
public void doAThing(Runnable r) {
r.run();
}
Third, write a method with the correct signature.
public class MyClass {
public void runAThing() {
System.out.println("I executed!");
}
}
Fourth, call the function passing in a method reference.
MyClass mc = new MyClass();
doAThing(mc::runAThing);
You'll note that none of the classes you've wrote ever explicitly implements Runnable. This is handled for you by the compiler.
You can do something similar using a lamdba expression:
doAThing(() -> System.out.println("I executed as a lamdba expression!"));
To return the function as a value from another function, just return an instance of Runnable.
Methods are not first class objecs in Java, apart from the already existing usage in reflection, to answer your questions:
Yes, you can pass it on, but it needs to satisfy the signature.
For a void method() you use a Runnable, like this:
Runnable method = this::method if it is in the same class, and then run the actual method with method.run().
However for a double method() you need to use a DoubleSupplier, like this:
DoubleSupplier method = this::method, and then use it as double d = method.get().
And many more signatures, and you can even define your own with Functional Interfaces.
Yes it is possible, but only specific signatures as shown in Point 1.
Lambdas behave exactly as anonymous inner classes, which are closures by itself, Java has had support for closures since they introduced anonymous inner classes. The only thing that is added now is that the syntax is much prettier.
No, not first class functions. Lambda expression are wrapped in a interface, and some syntatic sugar applied for brevity.
But you can;t create a function on its own and pass it around different methods, whether thats a key point or not is a different question.

Is it possible for a class to implement two interfaces, each of which contains a method with the same method header? [duplicate]

This question already has answers here:
Two interfaces with same method signature implemented in Java class
(7 answers)
Closed 9 years ago.
I was asked this is an interview, and have not found an answer.
Is that possible?
Yes it's possible. That won't make any difference. Your class still have to provide a single method definition. And that will satisfy contract of both the interfaces.
It is acceptable, though if the two interfaces provide for a different contract or different expected behavior, your code may encounter issues from subtle, hard-to-debug issues as you could pass the object to a method that expects the intricacies of one interface but encounters intricacies of the other.
Yes, it's possible. If both prototypes, or method headers, are the same, you simply write the method in your class, and you've inherently satisfied the contract with both interfaces (assuming all other methods are also included).
The interface does not tell you how to implement something, it is a contract that mandates that certain methods appear in classes that implement the interface. Now, there may be an issue with "expected" conflicting behavior; but, if by design, you're supposed to implement both interfaces, this is a perfectly acceptable practice.
EDIT: Here's a (requested) example:
public interface One
{
void test(String x);
}
public interface Two
{
void test(String x);
}
public class InterfaceTest implements One, Two
{
public void test(String s)
{
System.out.println(s);
}
}
Yes it is possible. There are some interfaces that have no required methods at all. Serializable is one.

Categories