Polymorphic uncurried method calls (adhoc polymorphism) in Java -
let me start example.
say have abstract vehicle
class.
public abstract class vehicle { public vehicle() {} public abstract void ride(); }
and classes car
, bicycle
inherit abstract class.
public class car extends vehicle { public car() {} @override public void ride() { system.out.println("riding car."); } } public class bicycle extends vehicle { public bicycle() {} @override public void ride() { system.out.println("riding bicycle."); } }
when apply ride()
method object of type vehicle
actual type can determined @ runtime, jvm apply correct version of ride()
.
that is, in curried method call of sort v.ride()
, polymorphism works expected way.
but if have external implementation in form of method accepts subtype of vehicle
argument? so, if have repair(bicycle b)
, repair(car c)
methods? uncurried polymorphic method call repair(v)
won't work.
example:
import java.util.arraylist; import java.util.list; public class main { private static void playwithvehicle() { list<vehicle> garage = new arraylist<vehicle>(); garage.add(new car()); garage.add(new car()); garage.add(new bicycle()); garage.foreach((v) -> v.ride()); // works. garage.foreach((v) -> { /* nice have. repair(v.casttoruntimetype()); */ // ugly solution, obvious way can think of. switch (v.getclass().getname()) { case "bicycle": repair((bicycle) v); break; case "car": repair((car) v); break; default: break; } }); } private static void repair(bicycle b) { system.out.println("repairing bicycle."); } private static void repair(car c) { system.out.println("repairing car."); } public static void main(string[] args) { playwithvehicle(); } }
i have check class name , downcast. there better solution this?
edit: actual purpose i'm traversing abstract syntax tree , happened notice want double dispatch.
ast
abstract class actual ast nodes assign
, methodcall
, or returnstmt
inherit. body
polymorphic list of ast
s.
code snippet:
list<ast> body; body.parallelstream().foreach((ast) -> { // 1 won't work. visit(ast); // 1 work. if (ast instanceof assign) { visit((assign) ast); } else if (ast instance of methodcall) { visit((methodcall) ast); } else if (ast instance of returnstmt) { visit((returnstmt) ast); } // etc. other ast nodes }); private void visit(assign ast) { } private void visit(methodcall ast) { } private void visit(returnstmt ast) { }
my possibilities of achieving double dispatch either checking class , downcasting or implementing visitor pattern, right?
answer: there no multiple dispatch in java , can simulated instanceof
or visitor pattern.
see here: java method overloading + double dispatch
see here: https://en.wikipedia.org/wiki/multiple_dispatch#examples_of_emulating_multiple_dispatch
on sidenote, possible in c# dynamic
calls: how build double dispatch using extensions
and possible in many languages compiled jvm bytecode, e.g. groovy mentioned.
Comments
Post a Comment