jeudi 11 janvier 2018

How to use a Double Dispatch with overload in JAVA?

I'm trying to create a double dispatch in JAVA to use overloaded methods.

public abstract class ComposantOrdi {
    protected void equiv(ComposantOrdi c){
        Equivalence.equiv(this, c);
    }
}

public class Montage extends ComposantOrdi{
    protected void equiv(Montage montage){
        Equivalence.equiv(this, montage);
    }
}

public class Equivalence {
    public static void equiv(Montage m, ComposantOrdi c){
        System.out.println("Montage - ComposantOrdi");
    }

    public static void equiv(Montage m, Montage c){
        System.out.println("Montage - Montage");
    }

    public static void equiv(ComposantOrdi m, ComposantOrdi c){
        System.out.println("ComposantOrdi - ComposantOrdi");
    }
}

For the example i create two objects

Montage m2 = new Montage();
ComposantOrdi m3 = new Montage();

m3.equiv(m2);
m3.equiv(m3);
m3.equiv((Montage)m3);

The result is :

ComposantOrdi - ComposantOrdi
ComposantOrdi - ComposantOrdi
ComposantOrdi - ComposantOrdi

But i would like to use overloaded method from Montage class and get something like this :

Montage - Montage
Montage - Montage
Montage - Montage

I probably didn't understand the double dispatch but could you tell me what I'm doing wrong please?

Aucun commentaire:

Enregistrer un commentaire