Chapter 4 · SimulationDynamic Binding: Which Method Runs?? ← Chapter 4 r = new(); RandomClass hierarchyMain.javaRunning methodOutput (console) ◀ Back Step ▶ Play Reset Try it yourself Correct 0 / 0 CloseDynamic Binding: Which Method Runs?Purpose: in a line such as Animal r = new Dog(); there are two types: the reference type of the variable (the declared type, Animal) and the object type of the object (the real type, Dog). A call is resolved in two stages: the compiler looks at the reference type and asks "does this method exist?"; the JVM looks at the object type at run time and asks "which version?".How to use itAt the top, choose the reference type, the object type and the call (or press Random).Step ▶ / ◀ Back (→ / ← on the keyboard), Play, Reset. In the hierarchy, the dashed blue outline marks the reference type and the red outline marks the object type; the blue rows are the compiler's search and the red rows are the JVM's search.Try it yourself: predict whether the code compiles, which version runs, and the output.RulesAn assignment compiles only if the object type is a subtype of the reference type (Animal r = new Dog(); is valid, Dog r = new Animal(); is not).The compiler searches for the method starting at the reference type and going up; if it cannot find it, it reports a compile error, whatever the object is.Instance methods are dynamically bound: the JVM starts the search at the object's real class and runs the first version it finds going up. A call such as name() made from inside a method of the superclass (this.name()) is resolved the same way.The choice among static methods and overloaded versions is not dynamic: the compiler chooses by the reference type.super.speak() is not dynamically bound: the version in the direct superclass runs.The downcast (Dog) r compiles but is checked at run time; if the object is not a Dog, ClassCastException is thrown. A cast between unrelated types (Cat → Dog) does not compile at all.ClassesEvery combination of reference type, object type and call (180 cases) was verified by compiling with javac --release 8 and running on Java 8; the compiler messages and outputs are the real results.Related slides: Chapter 4.4 · Polymorphism (Reference Type and Object Type, Dynamic Binding, Method Lookup: Bottom to Top, What Is Not Dynamically Bound?, Overloading at Compile Time) and Chapter 4.3 · Inheritance (The super Keyword, Method Overriding).