Java---方法引用(JDK1.8)

引用:对象引用,对象引用的本质在于为一个对象起别名,即:不同的栈内存可以同时指向同一块堆内存空间。
与对象引用类似的情况是,方法引用,即:为方法设置别名。


在JDK 1.8之中针对于方法引用提供有如下的四种形式:

· 引用静态方法:“类名称 :: static方法名称”;
· 引用某个对象的方法:“实例化对象 :: 普通方法”;
· 引用某个特定类的方法:“类名称 :: 普通方法”;
· 引用构造方法:“类名称 :: new”。


引用静态方法:

interface Demos{
    public void fun(T t);
}
public class Test {
    public static void main(String[] args) {
        Demos demo = System.out :: println ;
        demo.fun("Hello World!");
    }
}

引用某个对象的方法:

interface Demos{
    public T fun();
}
public class Test {
    public static void main(String[] args) {
        Demos demo = "Hello World!" :: toUpperCase ;
        System.out.println(demo.fun());
    }

引用某个特定类的方法:

interface Demos{
    public R fun(T t1,T t2);
}
public class Test {
    public static void main(String[] args) {
        Demos demo = String :: equals ;
        System.out.println(demo.fun("H

引用构造方法:

interface Demos{
    public R fun(T t,B b);
}
class Fruit{
    private String name;
    private double price;
    public Fruit(String name, double price) {
        super();
        this.name = name;
        this.price = price;
    }
    @Override
    public String toString() {
        return "Fruit [name=" + name + ", price=" + price + "]";
    }
}
public class Test {
    public static void main(String[] args) {
        Demos demo = Fruit :: new ;
        System.out.println(demo.fun("西瓜",20.16));
    }
}

你可能感兴趣的:(Java基础)