Java接口和Lambda函数
import java.util.Scanner;
public class Demo02 {
public static void main(String[] args) throws Exception {
// 修饰代表: 只有一个抽象方法
@FunctionalInterface
interface Power {
// 先声明
int template(int a, int b);
}
// 后定义
Power pow = (int numBot, int numTop) -> {
int result = 1;
if (numTop < 0) {
return -1;
}
while (numTop-- != 0) {
result *= numBot;
}
return result;
};
/*
* 实际上:
* Power pow = new Power() {
*
* @Override
* public int template(int numBot, int numTop) {
*
* int result = 1;
* if (numTop < 0) {
* return -1;
* }
*
* while (numTop-- != 0) {
* result *= numBot;
* }
*
* return result;
*
* }
* };
*/
// 这里其实就是继承和多态重写的方法,后期调用需要 pow.template(), 真的好别扭.
// Java 包袱太沉重了,啥啥要用类包装,太执念了.
/*
* Similarly in CPP:
*
* std::function<int(int, int)> mypowFunc;
* mypowFunc = [](int numBot, int numTop){
* . . .
*
* return result;
* }
*
*/
System.out.print("Type a numBot: ");
Scanner sc = new Scanner(System.in);
int numBot = sc.nextInt();
System.out.print("Type a numTop: ");
int numTop = sc.nextInt();
sc.close();
System.out.printf("\n%d's to %dth power is %d.", numBot, numTop, pow.template(numBot, numTop));
}
}