Dynamische Bindung

LZoellner

Mitglied
Hallo,
mir ist die dynamische Bindung nicht ganz eingängig.
Dazu folgendes Beispiel:

Java:
public class A {
public int f(int i){ return i+1; }
public int f(String s){ return 7;}
public int g() { return h()+f(0);}
public int h() { return 20; }
public int h(Object o){return 15;}
}

public class B extends A {
public int f(int i) { return i+2; }
public int f(Object o){ return 99;}
public int g(){return super.g()*2;}
public int h(int x){return 30 + x;}
public int h(String s){ return 52;}
}

public class ABC {
public static void main(String[] args) {
String s = "Inheritance";
a = new B();
System.out.println("a.f(0) = " + a.f(0));
System.out.println("a.g() = " + a.g()) ;
System.out.println("a.f(s) = " + a.f(s));
System.out.println("a.h(s) = " + a.h(s));
}

Ergibt folgende Ausgaben:
a.f() = 2
a.g() = 44
a.f(s) = 7
a.h(s) = 15

a.f(0) = 2 ist klar, weil f(0) in B überschrieben wird und somit besser als f(0) in A passt.

a.g() = 44 ist glaube ich auch klar, weil wieder f(0) verwendet wird, die Methode h() allerdings nicht überschrieben, sondern nur überladen wird und somit nach wie vor h() aus A verwendet wird und nicht h() aus B. Ist das korrekt?

a.f(s) = 7 weil f(String s) in A spezifischer ist als f(Object) in B und somit f(String) besser passt. Ist das korrekt?

a.h(s) = 15
Das verstehe ich nicht. Warum wird hier h(Object) aus A verwendet und nicht h(String s) aus B, da h(String s) ja spezfischer wäre und somit besser passt.

Freue mich über Antworten.
LG
 
Zuletzt bearbeitet:

Neue Themen


Zurück
Oben