I have a Java puzzle I'm having trouble solving. Given the following three classes:
public class A1 {
protected boolean foo() {
return true;
}
}
public class B1 extends A1 {
}
public class C1 {
private static boolean secret = false;
public boolean foo() {
secret = !secret;
return secret;
}
public static void main(String[] args) {
C1 c = new C1();
for (int i = 0; i < args.length; i++) {
c.foo();
}
A1 a = new B1();
if (a.foo() == c.foo()) {
System.out.println("success!");
}
}
}
I need to complete the class B1 , however I want, without change the classes A1
and C1
or adding new files, such that for at least one argument, C1
will always print the string "success!".
I think that I need to override the method foo()
of the class A1
,
and rewrite it by getting the number of arguments from the main function on C1
, to get the right return value.
My problem is that I don't know how to do that. (Remember that I'm not allowed to solve this problem by writing A1 a = new B1(args.length)
instead of A1 a = new B1()
. That'd be too easy.)
Any suggestions on how to do it, or even totally different solutions, would be appreciated!
Since secret
is static, you could just create a new C1
and call foo
on that, just be sure to invert the result as well:
class B1 extends A1 {
public boolean foo() {
return !(new C1().foo());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With