Je lis à propos covariant return types in Java. j'ai écrit le code suivant:Object.clone() dans javap lors de l'utilisation des types de retour covariants en Java
Une classe parente:
package other;
public class Super implements Cloneable {
@Override
public Super clone() throws CloneNotSupportedException {
return (Super) super.clone();
}
}
Une classe enfant:
package other;
public class Sub extends Super {
@Override
public Sub clone() throws CloneNotSupportedException {
return (Sub) super.clone();
}
}
Comment je l'utilise:
package com.sample;
import other.Sub;
import other.Super;
public class Main {
public static void main(String[] args) throws Exception {
Super aSuper = new Super();
Super bSuper = aSuper.clone();
System.out.println(aSuper == bSuper); // false
Sub aSub = new Sub();
Sub bSub = aSub.clone();
System.out.println(aSub == bSub); // false
}
}
Si c'est OK pour revenir un sous-type lors de la substitution d'une méthode (comme vous le voyez, c'est ce que je fais avec clone()
dans Super
et Sub
), pourquoi est-ce que je vois Object.clone
dans Super
et Sub
quand je lance javap -p Super.class
et javap -p Sub.class
, respectivement?
Le résultat de javap -p Super.class
:
Compiled from "Super.java"
public class other.Super implements java.lang.Cloneable {
public other.Super();
public other.Super clone() throws java.lang.CloneNotSupportedException;
public java.lang.Object clone() throws java.lang.CloneNotSupportedException;
}
Le résultat de javap -p Sub.class
:
Compiled from "Sub.java"
public class other.Sub extends other.Super {
public other.Sub();
public other.Sub clone() throws java.lang.CloneNotSupportedException;
public other.Super clone() throws java.lang.CloneNotSupportedException;
public java.lang.Object clone() throws java.lang.CloneNotSupportedException;
}
Pourquoi demandez-vous, lorsque l'article parle explicitement que vous avez lié au sujet ** 'méthodes générées par javac' ** (également connu sous le nom de méthodes * bridge *) dans la section intitulée "** Comment cela est-il implémenté?" "?" Avez-vous réellement * lu * l'article lié? – Andreas