The Rules of Dynamic Method Selection

  • Compiler allows memory box to hold any subtype.

  • Compiler allows calls based on static type.

  • Overridden non-static methods are selected at run time based on dynamic type.

    Everything else is based on static type, including overloaded methods. Note: No overloaded method for problem at left.

强制类型转换会改变 static type(compiler-tyep) 但不会改变 dynamic-type. Object o2 = new showDog(…); Dog dx = ((Dog) o2) ;

dx.bark() //会执行 showDog 中的 bark 方法

Contents