<< January 3, 2008 | Home | January 5, 2008 >>

Friday Java Quiz: Know Your java.lang.Object Class

Warm Up Q: Without the help of your IDE or looking at the Javadoc, list all methods of the java.lang.Object class.

Q: Will the following program compile? Run? Print anything? If so, what?

public class Foo implements Cloneable {
  private int i;

  public Foo(int i) {
    this.i = i;
  }

  public int getI() {
    return i;
  }

  public static void main(String[] args) throws Throwable {
    Foo foo1 = new Foo(1024);
    Foo foo2 = (Foo) foo1.clone();
    System.out.println(foo2.getI());
  }
}

Follow Up Q 1: How would things change if the following method is added:

  public Object clone() throws CloneNotSupportedException {
    return super.clone();
  }

Follow Up Q 2: How about this?

  public Object clone() throws CloneNotSupportedException {
    Foo clone = (Foo) super.clone();
    clone.i = this.i;
  }

Again, no actually running the compiler, etc., etc., ...

Tags :