【发布时间】:2015-06-08 15:59:55
【问题描述】:
我得到了 A 和 C 类,我应该编写 B 类,这使得 C 类中的 main 输出始终为 successful! 。
正弦有一个随机布尔变量,只有当它为假时我才会得到一个好的结果,当它为真时我没有得到输出。
我不允许在 A 或 C 类中进行任何更改。
我知道问题出在C 类中的第三个if,但是我可以在B 类中进行哪些更改以防止进入这个if?
public class A {
public String foo(String s) {
return s;
}
}
public class B extends A {
public A getA(boolean flag){
A a = new A();
if (flag){
return(a);
}
else{
return (a);
}
}
}
package sw1.riddles.second;
import java.util.Random;
public class C {
public static void main(String[] args) {
String input = args[0];
B b = new B();
Random random = new Random();
boolean randomBool = random.nextBoolean();
A a = b.getA(randomBool);
if (randomBool) {
if (!input.equals(a.foo(input))) {
return;
}
} else {
if (!(input+input).equals(a.foo(input))) {
return;
}
}
System.out.println("success!");
}
}
【问题讨论】:
-
A不是最终的,因此您可以使用B.getA中的匿名子类覆盖它,这取决于您的标志。这里的目的是什么?看起来很奇怪的学校作业。 -
不需要匿名子类。只需覆盖 B 中的 foo() 并在 flag 为 false 时返回
this。 -
您不能联系
return。所以 a.foo(input) 必须返回input(randomBool) 或input+input(!randomBool)。所以b.getA(randomBool)必须返回不同的东西。
标签: java class oop if-statement