【问题标题】:Static/dynamic binding in JavaJava中的静态/动态绑定
【发布时间】:2018-08-27 09:39:50
【问题描述】:

我确实有class Person, class StudentStudent extends Person。据我了解,静态绑定如下:

class Person {
   talk(Person p) {
      print("Hi by person.");
   } 
}

class Student extends Person {
   talk(Student s) {
      print("Hi by stud.");
   }
}

现在如果我实例化并调用方法:

Person x = new Student();
talk(x);                      
// output: "Hi by person." because of static binding, am I right?

我的问题: 如果只有class Student 有一个方法talk(Student s) 会怎样。现在我打电话给talk(x)。由于我通常应该从class Person 获取talk() 方法,如果没有这样的方法会发生什么?

编辑:我尝试运行它,但它给了我一个编译错误。好的,但是为什么会发生这种情况?我了解到编译器会先去子类搜索方法,如果有,就执行?

【问题讨论】:

  • 你试过制作那个程序吗?
  • 其实我没有你说的对,但不管结果如何,我也对它背后的规则感兴趣。
  • @JushKillaB “为什么?”什么?
  • "如果只有类 Student 有一个方法 talk(Student s)" - 你试过吗?提示:它编译了吗?
  • 运行它,没有编译,但我不明白。为什么它不在其子类class Student 中寻找talk() 方法?

标签: java compilation dynamic-binding static-binding


【解决方案1】:

重载方法不存在动态绑定...

Student 是一个 Person 所以方法从 Person 调用

【讨论】:

  • 这还远远不够清楚......例如“Student is a Person”实际上意味着引用 x 是对Person,不是Student extends Person
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多