Java Puzzle 6: Chicken or the Egg

Mar 22, 2012

Which was first, the chicken or the egg?

What if every egg got the secret answer to that question imprinted from the chicken that laid it?

package chicken;

public class Egg {
    final Object first;

    public Egg(Chicken mom) {
        first = mom.first;
    }
}

And if then every chicken got that knowledge from the egg, passing it on from generation to generation. Then we could just ask any chicken!

package chicken;

public class Chicken {
    final Object first;

    public Chicken(Egg egg) {
        first = egg.first;
    }

    public void ask() {
        // The goal is to reach this line
        System.out.println("First there was the " + first);
    }
}

Now all you need to figure out is how to create the egg to create the chicken to create the egg to create chicken to ask the question.
Here's a naive attempt that will throw a NullPointerException. Can you edit it to make it work?

package creator;

import chicken.Chicken;

public class Creator {
    public static void main(String[] args) {
        new Chicken(null).ask();
    }
}

The same rules and system as usual apply: you must run with the security manager enabled (-Djava.security.manager). Your solution must be in the creator package. If you found the solution, post it as a comment here below. These comments stay private, and become public later on the next blog post.

Good luck solving the mystery!