需求:
在测试类Test中创建A的对象a并调用成员方法methodA(),要求用两种方式实现
自己书写,不要用idea自动生成。
public class Test {
public static void main(String[] args) {
}
}
//定义接口
interface InterA {
void showA();
}
class A {
public void methodA(InterA a) {
a.showA();
}
}
public class Test {
public static void main(String[] args) {
//方法一:创建了A的对象a后,直接使用a调用methodA(InterA a)方法,
//其中要传入的参数直接用匿名内部类代替
A a = new A();
a.methodA(
new InterA() {
@Override
public void showA() {
System.out.println("诶嘿✧✧✧");
}
}
);
//方法二:创建一个实现了InterA接口的类,创建其对象后,
//将其作为参数交给A的对象进行调用
a.methodA(new getInterA());
}
}
//定义接口
interface InterA {
void showA();
}
//实现InterA接口的类
class getInterA implements InterA{
@Override
public void showA(){
System.out.println("啊哈~~~");
}
}
class A {
public void methodA(InterA a) {
a.showA();
}
}