【java基础】接口是否能有实现类?

接口是否能有实现方法
我的回答: 当然可以

java8以后就允许接口有实现方法:

  • default修饰的方法
  • static修饰的方法

/**
 * 能用lambda的情况,接口里面只有一个未实现的方法
 * 保证函数式接口@FunctionalInterface,如果有两个方法就会报错
 */
public class LambdaDemo {

    @FunctionalInterface
    interface Age {
        int add(int x, int y);
        //可以随便有几个default
        default int add2(int x, int y){
            return x + y + 2;
        };
        //static方法也可以有方法体,可以随便写几个
        public static int add3(int i, int y) {
            return i + y;
        }
    }

    public static void main(String[] args) {
        Age age = (int x , int y)-> {
            return x + y;
        };

        System.out.println("" + age.add(2,3));
        System.out.println("Age" + Age.add3(3,4));
    }
}

可以关注我的公众号一起学习

猜你喜欢

转载自www.cnblogs.com/amberbar/p/11809649.html