Why javac adds clone-method and how java separates and links methods with same signature?

41 views Asked by At

Let's look at the following example.

public class T1 implements Cloneable {
    private T1(T1 g) {}

    public T1 clone() { return new T1(this); }
}

There are two clone methods in a bytecode.

$ javac T1.java
$ javap -s T1
Compiled from "T1.java"
public class T1 implements java.lang.Cloneable {
  public T1 clone();
    descriptor: ()LT1;

  public java.lang.Object clone() throws java.lang.CloneNotSupportedException;
    descriptor: ()Ljava/lang/Object;
}

These two methods have different result type and the same input signature. If I try to add a second method to code I will get a compile time error.

    public T1     clone() { return new T1(this); }
    public Object clone() { return null; }
...
$ java T1.java
T1.java:7: error: method clone() is already defined in class T1
    public Object clone() { return (null); }

So why javac adds the second method? And how java links methods with the same input signature?

0

There are 0 answers