interface Example{
void methodExample();
}
class Y{
void do(Example x) { }
}
class X{
void methodX() {
Y y = new Y();
y.do(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
我想创建一个主类并调用methodExample
。我该怎么做?
答案 0 :(得分:3)
由于您的类实现了Example
接口,并且因为该接口上存在void methodExample()
,您需要做的就是通过其接口引用该对象,并调用其方法:
class Y{
public void doIt(Example x) {
x.methodExample();
}
}
上述工作,因为实现Example
的所有类的对象,包括所有匿名实现,在编译时都是已知的,以实现methodExample()
。
答案 1 :(得分:1)
如果您无法访问类Y
那么,唯一的方法是先使用匿名内部类重写doIt()
,然后调用重写方法,例如:< / p>
class X {
void methodX() {
Y y = new Y() {
@Override
void doIt(Example x) {
x.methodExample();
}
};
y.doIt(new Example() {
public void methodExample() {
System.out.println("methodExample");
}
});
}
}
要拨打此电话,您只需执行以下操作:
public static void main(String[] args) throws Exception {
X x = new X();
x.methodX();
}