[英]Method with an Interface as a parameter
class Do{
void doit(){
ClassA a = new ClassA();
a.doSomething(>>>CODE HERE<<<);
}
}
interface InterfaceA{
void doSomethingElse();
}
class ClassA{
void doSomething(InterfaceA f){
}
}
问题:完成上面的代码,以便doit方法显示“ Hello world!”。 通过仅在所示的括号之间添加代码,而不更改其他任何内容。
有人可以帮我解决这个问题吗? 我仍然没有头绪。 昨天我在测验中把它留为空白:((。感谢您的帮助
class Do{
void doit(){
ClassA a = new ClassA();
a.doSomething(new InterfaceA () {
{ System.out.println("Hello world"); }
@Override public void doSomethingElse() { }
});
}
}
关键是使用初始化程序定义一个匿名类,然后使用“ new”创建该类的新对象。 创建对象将执行初始化程序。 PS这已经过测试。
这似乎不是一个很好的测验问题。 做这样的事情是很模糊的,可能不是人们通常会编写的正常事情。 它看起来比实际的测试问题更像是一个难题。 除非有更好的答案,否则我不会发现...
OK, 如果测验问题看起来像这样:
class Do{
void doit(){
ClassA a = new ClassA();
a.doSomething(>>>CODE HERE<<<);
}
}
interface InterfaceA{
void doSomethingElse();
}
class ClassA{
void doSomething(InterfaceA f){
// NOTE THIS CHANGE!
f.doSomethingElse();
}
}
然后,您可以更改此设置:
a.doSomething(>>>CODE HERE<<<);
对此:
a.doSomething(new InterfaceA() {
@Override public void doSomethingElse() {
System.out.println("Hello world!");
}
});
否则答案就像其他答案所说的那样有些奇怪。
我不知道这是否是测验的预期答案,但这应该可行:
class Do{
void doit(){
ClassA a = new ClassA();
a.doSomething(null); System.out.println("Hello world!");
// ^ starting paren closing paren ^
}
}
interface InterfaceA{
void doSomethingElse();
}
class ClassA{
void doSomething(InterfaceA f){
}
}
基本上,只要将两行放在同一行上,就不必为接口提供实现。 这样,唯一添加的代码为null); System.out.println("Hello world!"
null); System.out.println("Hello world!"
灵感来源: http : //xkcd.com/327/
对于可能是技术测验的问题,这可能更像是一个谜语般的答案……除非您的老师想和您一起玩一些乐趣。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.