Skip to content

Instantly share code, notes, and snippets.

@piotrMocz
Created April 13, 2015 22:24
Show Gist options
  • Save piotrMocz/742b5400f33c136b0fac to your computer and use it in GitHub Desktop.
Save piotrMocz/742b5400f33c136b0fac to your computer and use it in GitHub Desktop.
Single vs. Multiple dispatch
// przyklad ma na celu zobrazowanie czym rozni sie multiple dispatch od single dispatch.
public class DispatchTest {
public static void main(String[] args) {
Foo foo = new Bar(); // typ statyczny: Foo, typ runtime'owy: Bar
A a = new B(); // typ statyczny: A, typ runtime'owy: B
foo.fooMethod(a); // wolamy tak, by dac szanse kompilatorowi sie wykazac (dwa razy inny typ
// dynamiczny i statyczny)
}
}
class Foo {
void fooMethod(A a) {
System.out.println("Foo::fooMethod(A)");
a.aMethod();
}
void fooMethod(B b) {
System.out.println("Foo::fooMethod(B)");
b.aMethod();
}
}
class Bar extends Foo {
// single dispatch! kompilator wzial pod uwage typ runtime'owy tylko
// "wyroznionego" argumentu przed kropka.
void fooMethod(A a) {
System.out.println("Bar::fooMethod(A)");
a.aMethod();
}
// gdybysmy mieli multiple dispatch, to wywolaloby sie to.
// (wziety pod uwage runtime'owy typ obydwu argumentow na raz)
void fooMethod(B b) {
System.out.println("Bar::fooMethod(B)");
b.aMethod();
}
}
class A {
void aMethod() {
System.out.println("A::aMethod");
}
}
class B extends A {
// nawet pomimo single-dispatch wywola sie ta metoda:
// wybor typu runtime'owego nastapi dopiero przy wywolaniu w linii 28
void aMethod() {
System.out.println("B::aMethod");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment