Java多态顶级方法被调用

r7s23pms  于 2024-01-05  发布在  Java
关注(0)|答案(2)|浏览(157)

我在java项目中有一个继承的对象,我试图调用子对象中的overriden方法。由于某种原因,该方法的父版本被调用。我对多态性的理解是,方法的最低版本总是被调用。为什么父版本被调用?

  1. public class Generator
  2. {
  3. public static void acceptPending()
  4. {
  5. System.out.println("top level is called");
  6. }
  7. }
  8. public class GeneratorNeo extends Generator
  9. {
  10. public static void acceptPending()
  11. {
  12. System.out.println("neo level is called");
  13. }
  14. }
  15. public class Driver()
  16. {
  17. public static void main(String[] args)
  18. {
  19. Generator gen = null;
  20. gen = new GeneratorNeo();
  21. gen.acceptPending(); // prints top level is called
  22. }
  23. }

字符串

4szc88ey

4szc88ey1#

acceptPending是一个静态方法,静态方法是根据对象的编译时类型调用的ie Parent类型。不像示例方法。
因此从这两个类中删除static关键字将为您提供给予预期的行为。

o3imoua4

o3imoua42#

  1. public class Generator {
  2. public void acceptPending() {
  3. System.out.println("top level is called");
  4. }
  5. }
  6. public class GeneratorNeo extends Generator {
  7. @Override
  8. public void acceptPending() {
  9. System.out.println("neo level is called");
  10. }
  11. }
  12. public class Driver {
  13. public static void main(String[] args) {
  14. Generator gen = null;
  15. gen = new GeneratorNeo();
  16. gen.acceptPending(); // prints neo level is called
  17. }
  18. }

字符串

展开查看全部

相关问题