常量:默认是 public static final
方法:默认是 public abstract
在JAVA8中,增加了默认方法(public default),静态方法(public static)
在JAVA9中,增加了私有方法
public interface eatable {
// 抽象方法 实现类 必须进行实现
void funAbstract();
// 默认方法 和 静态方法 都需要方法体
default void funDefault(){
System.out.println("默认方法");
}
static void funStatic(){
System.out.println("静态方法");
}
}
public static void main(String[] args) {
// 实现 抽象方法 并调用 默认方法
((eatable) () -> System.out.println("实现抽象方法")).funDefault();
// 实现 抽象方法 并调用 抽象方法
((eatable) () -> System.out.println("实现抽象方法")).funAbstract();
// 接口中的静态方法 只能被 接口调用, 不能被实现类调用
eatable.funStatic(); // OK
((eatable) () -> System.out.println("实现抽象方法")).funStatic(); // Error
}
方法引用(使用已有的方法逻辑去处理接口中的那个抽象方法)
引用 类中的 静态方法
// 抽象方法的参数 全部传递给 被引用的静态方法
public static void main(String[] args) {
((eatable) s -> Integer.parseInt(s)) // lambda 形式
.toInt("2349645");
((eatable) Integer::parseInt) // 类名::静态方法
.toInt("23");
}
interface eatable {
void toInt(String s);
}
引用 类中的 非静态方法
// 抽象方法的参数 全部传递给 被引用的非静态方法
public static void main(String[] args) {
((eatable)s -> System.out.println(s.toUpperCase()))
.toUpper("fdf");
((eatable)new linshi()::printString)
.toUpper("fsdf"); // 借助对象 , 引用类中的非静态方法
}
class linshi {
public void printString(String s){
System.out.println(s.toUpperCase());
}
}
interface eatable {
void toUpper(String s);
}
也可以这样:
但注意:接口中的那个抽象方法 第一个参数的参数类型 得是 linshi,后面的参数传给了 printString 方法。
public static void main(String[] args) {
((eatable)(s,a) -> System.out.println(a.toUpperCase()))
.toUpper(new linshi(),"fgwerg");
((eatable)linshi::printString)
.toUpper(new linshi(),"grg");
}
class linshi {
public void printString(String s){
System.out.println(s.toUpperCase());
}
}
interface eatable { // 第一个参数 作为调用者
void toUpper(linshi a,String s); // 第二个参数 给到 printString 方法去作为参数
}



