Ahti Kitsik
Building tools with Python, Java, Go, JS. For enquiries email inbox@ahtik.com

writings biography

Java Quiz of The Day - same private field instance for two classes

01 Dec 2008 by @ahtik

What is the smallest change to main method that makes it sysout "true"?

You are allowed to change ONLY the main method! Of course changing sysout line is out of question.

You can leave your answer in comments and I'll publish/approve them together with the solution.

public class InstanceDemo {

public static void main(String[] args){
MyClass cl1 = new MyClass();
MyClass cl2 = new MyClass();
System.out.println(cl1.ocl==cl2.ocl && cl1!=cl2);

private static class MyClass extends java.util.ArrayList {
private final Object ocl = new Object();


I'll post the correct answer in 24h :)

UPDATE: Was not that hard afterall! :) ~45 correct answers.

Yes, clone() was the answer I was looking for:
[java]MyClass cl2 = (MyClass) cl1.clone();[/java]

Ed Merks surprised with a nice solution:
//Add this line as the first line of main.
class MyClass extends InstanceDemo.MyClass {
Object ocl = null;

And a lot of people took the hard-core way:
Field field = cl1.getClass().getDeclaredField("ocl");

@ahtik is on twitter!