栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

接口的组成和方法引用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

接口的组成和方法引用

接口的组成

常量:默认是 public static final
方法:默认是 public abstract
在JAVA8中,增加了默认方法(public default),静态方法(public static)
在JAVA9中,增加了私有方法

For Instance
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 方法去作为参数
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1004314.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号