start‎ > ‎

code2 chicken/egg

code1, code2, code3

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?

1
2
3
4
5
6
7
8
9
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!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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?

1
2
3
4
5
6
7
8
9
package creator;
 
import chicken.Chicken;
 
public class Creator {
    public static void main(String[] args) {
        new Chicken(null).ask();
    }
}
Comments