🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: borland.public.jbuilder.java.language
Article #17943

Double dispatching technique (Visitor pattern)

#17943
From: Edoardo Comar
Date: Wed, 02 Sep 1998 00:00
88 lines
2279 bytes
Does the double dispatching technique of GOF's Visitor pattern not always
work in Java ?

I saw that if you have an overloaded method of which a version take as an
argument an object of class A,
and another takes an object of class B which extends A, if you invoke it
with a reference of type A which points to
a class B object, the JVM selects the first version (the one which declares
an instance of class A as its parameter).

Is this behavior correct ?

If you like, play with this sample of mine.
=======
package edotest;

public class Fruit
{
  public void print()     // (3)
  {
    System.out.println("Fruit");
  }
}
=======
package edotest;

public class Apple extends Fruit
{
  public void print()  // (4)
  {
    System.out.println("Apple");
  }
}
=======
package edotest;

public class Main
{
  Fruit fruit = new Fruit();
  Apple apple = new Apple();
  Fruit fruit2 = new Apple();

  public static void main(String[] args)
  {
    Main main = new Main();
    main.test();
  }


  void test()
  {
    print(fruit);   // invokes (1 + 3 )
    print(apple); // invokes (2+ 4 )
    print(fruit2); // invokes (1 + 4 )
  }


  void print(Fruit aFruit)        // (1)
  {
    System.out.print("Main.print(Fruit aFruit) : ");
    aFruit.print();
  }


  void print(Apple anApple) // (2)
  {
    System.out.print("Main.print(Apple anApple) : ");
    anApple.print();
  }

}
=======


bye,
Edo.

ing. Edoardo Comar
<comar@tecnest.it>
Tecnest S.r.l
via Tullio, 11/13 - 33100 Udine Italy
ph. +39 432 511550
fax +39 432 508725
--------
<e.comar@go.nettuno.it> (home email)
PGP RSA key on keyservers  http://wwwkeys.pgp.net
key ID 29365395  created 1994/11/03
fingerprint = 5E 10 E1 46 22 35 84 3D  3F 57 E0 35 BE 5C 1E A7
Technical Details
Message-ID: <6sjh8m$eq419@forums.borland.com>
Path: arc1-ca.pugleaf.net!unknown!not-for-mail

Show Full Headers
Complete Article Headers
X-Google-Language: ENGLISH,ASCII-7-bit
X-Google-Thread: f74b3,107ec690fdf39b4a,start
X-Google-Attributes: gidf74b3,public
From: "Edoardo Comar" <comar@tecnest.it>
Subject: Double dispatching technique (Visitor pattern)
Date: 1998/09/02
Message-ID: <6sjh8m$eq419@forums.borland.com>
X-Deja-AN: 387119530
Organization: Another Netscape Collabra Server User
X-Mimeole: Produced By Microsoft MimeOLE V4.72.2106.4
Newsgroups: borland.public.jbuilder.java.language