<< Given A Choice Between A Web UI And A RIA UI, ... | Home | Gmail Gives Me Choices: Ajax, POP3, and IMAP >>

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 :


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

I believe the code will run and print 1024. The clone method is protected but by default makes a bitwise copy of all fields.

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

That's the correct answer. The part that is a little bit surprising is that the Object.clone() method knows where the private field Foo.i is.


Add a comment Send a TrackBack