markdown FunctionalInterface
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown FunctionalInterface相关的知识,希望对你有一定的参考价值。
## Functional Interface
@FunctionalInterface
# Brief:
## Why we use Fuctional Interface?
### Answer: When the fuction defination is not fixed. OR we want use the same function for different puposes.
for example: Let's think about this method
```
String greeting(String name){
return "Hello " + name;
}
```
this method is working for english spoker. But what about spanish or Arabic people
so at this time we want this method to be abstract that means no defination or body just structure what fulfill idea not impplementation
```
@FunctionalInterface // this is optional if you want lamda then add this annotation
interface Greet{
String greeting(String name);
}
```
So now our Use case can be like
```
Greet myGreet;
switch(language){
case "en":
myGreet= name -> "hello" + name;
break;
case "ar":
myGreet= name -> "Salam" + name;
break;
}
System.out.println(myGreet.greeting("Tareq Islam"));
```
### I hope you understant what is the uses of abstract method. There is another good use of interface in Android as callback
### Features:
#### only one abstract method.
```
@FunctionalInterface
interface myFunction{
/*Only one abstract method*/
String Enhance(String s);
}
```
#### may have multiple defined method with default keyowrd
```
@FunctionalInterface
interface myFunction{
/*Only one abstract method*/
String Enhance(String s);
default String transorm(int i){
return ""+ i;
}
default void show(String s){
System.out.println(s);
}
}
```
#### may have any static method as well
```
@FunctionalInterface
interface myFunction{
/*Only one abstract method*/
String Enhance(String s);
default String transorm(int i){
return ""+ i;
}
default void show(String s){
System.out.println(s);
}
static int add(int a , int b){
return a+b;
}
}
```
#### lets think about this functional Interface
```
@FunctionalInterface
interface Greet{
/*Only one abstract method*/
String greeting(String s);
default String transorm(int i){
return ""+ i;
}
default void show(String s){
System.out.println(s);
}
static int add(int a , int b){
return a+b;
}
}
```
### Use of this Interface
#### Use of the abstract method
As we know for using any abstract method we need to define the method first
```
//with lamda
Greet myGreet= (s) -> {
return "Hello " + s;
};
```
Now we can use this abstract method by calling the method
```
String intro = myGreet.greeting("tareq Islam");
```
#### uses of defined method
For adding any functionality with existing interface we have to use define methods
```
//we need the Greet object
myGreet.show("tareq");
```
#### static methods: no need of the object
```
System.out.println(Greet.add(4, 6));
```
以上是关于markdown FunctionalInterface的主要内容,如果未能解决你的问题,请参考以下文章