MrSonic
MrSonic

Reputation: 363

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

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!

Upvotes: 6

Views: 140

Answers (2)

Jorn Vernee
Jorn Vernee

Reputation: 33865

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());
    }
}

Upvotes: 6

Egor
Egor

Reputation: 1409

Maybe I didn't understand question but I think

protected boolean foo() {
    return false;
}

In class B1 will be working

Upvotes: -2

Related Questions