引用对象的实例方法
格式:对象::成员方法
范例:"HelloWorld"::toUpperCase
String类中的方法:public String toUpperCase() 将此String所以字符转换为大写
练习
定义一个类(PrintString),里面定义一个方法
public void printUpper(String s):把字符串参数变成大写的数据,然后在控制台输出
定义一个接口(Printer),里面定义一个抽象方法
void printUpperCase(String s)
定义一个测试类(PrinterDemo),在测试类中提供两个方法
一个方法是usePrinter(Printer p)
一个方法是主方法,在主方法中调用usePrinter方法
package com.aynu22;public interface Printer {void printUpperCase(String s);
}
package com.aynu22;// 练习
//
// 定义一个类(PrintString),里面定义一个方法
// public void printUpper(String s):把字符串参数变成大写的数据,然后在控制台输出
// 定义一个接口(Printer),里面定义一个抽象方法
// void printUpperCase(String s)
// 定义一个测试类(PrinterDemo),在测试类中提供两个方法
// 一个方法是usePrinter(Printer p)
// 一个方法是主方法,在主方法中调用usePrinter方法import java.io.PrintStream;public class PrinterDemo {public static void main(String[] args) {//在主方法中调用usePrinter方法
// usePrinter((String s)-> {String result = s.toUpperCase();System.out.println(result);
// System.out.println(s.toUpperCase());
// });usePrinter(s -> System.out.println(s.toUpperCase()));//引用对象的实例方法PrintString ps = new PrintString();usePrinter(ps::printUpper);//Lambda表达式被对象的实例方法替代的时候,它的形式参数全部传递给该方法作为参数}private static void usePrinter(Printer p){p.printUpperCase("HelloWorld");}
}
package com.aynu22;public class PrintString {// public void printUpper(String s):把字符串参数变成大写的数据,然后在控制台输出public void printUpper(String s){String result = s.toUpperCase();System.out.println(result);}
}
HELLOWORLD
HELLOWORLD
引用类的实例方法
引用类的实例方法,其实就是引用类中的成员方法
格式:类名::成员方法
范例:String::substring
String类中的方法:public String substring(int beginIndex,int endIndex)
从beginIndex开始到endIndex结束,截取字符串,返回一个子串,子串的长度为endIndex-beginIndex
练习:
定义一个接口(MyString),里面定义一个抽象方法
String mySubString(String,int x,int y);
定义一个测试类(MyStringDemo),在测试类中提供两个方法
一个方法是:useMyString(MyString my)
一个方法是主方法,在主方法中调用useMyString()方法
package com.aynu23;public interface MyString {String mySubString(String s,int x,int y);
}
package com.aynu23;// 练习:
//
// 定义一个接口(MyString),里面定义一个抽象方法
// String mySubString(String s,int x,int y);
// 定义一个测试类(MyStringDemo),在测试类中提供两个方法
// 一个方法是:useMyString(MyString my)
// 一个方法是主方法,在主方法中调用useMyString()方法public class MyStringDemo {public static void main(String[] args) {//在主方法中调用useMyString()方法
// useMyString((String s,int x,int y)->{
// return s.substring(x,y);
// });useMyString(( s, x, y)->s.substring(x,y));//引用类的实例方法useMyString(String::substring);//Lombda表达式被类的实例方法替代的时候//第一个参数作为调用者//后面的参数全部传递给该方法作为参数}private static void useMyString(MyString my){String s = my.mySubString("HelloWorld", 2, 5);System.out.println(s);}
}