Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java puzzle accessing main's arguments without them being passed in

Tags:

java

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!

like image 665
MrSonic Avatar asked Sep 30 '18 17:09

MrSonic


1 Answers

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());
    }
}
like image 178
Jorn Vernee Avatar answered Nov 03 '22 19:11

Jorn Vernee