把一个类当做另一个类的方法中的参数,这是什么用法,求解答,谢谢。
2条回答 默认 最新
关注
给你举个例子你看下
方式一 方法接口
a 先定义一个接口(定义抽象方法,理解成函数参数的规范)
public interface MethodInterface {//这个方法假如就是你想要传递的方法 public String test(String s);
}
b 不同函数实现接口(具体的函数参数)
public class Method implements MethodInterface {
@Override
public String test(String s) {
return s;
}
}public class Method1 implements MethodInterface {
@Override
public String test(String s) {
return s+s;
}
}c 调用函数参数的方法(调用规范【接口】)
public class TestMethod {
//接口是我定义的 所以我知道接口中有test方法,参数为String
public void test(MethodInterface methodInterface){
System.out.println(methodInterface.test("test"));
}
}d 利用接口的多态实现多种方法的调用
@Test
public void test1(){
//testtest
new TestMethod().test(new Method1());
//test
new TestMethod().test(new Method());}
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报