由于在编译阶段,只是检查参数的引用类型。然而在运行时,Java虚拟机(JVM)指定对象的类型并且运行该对象的方法。因此在下面的例子中,b.move()之所以能编译成功,是因为Animal类中存在move方法,所以编译成功,然而运行时,运行的是特定对象的方法,即运行的是Dog类的move方法。而对Dog c而言,编译阶段首先是去Dog中查找bark(),因此能编译成功,同时也能运行成功;但是对于b.bark()而言,首先是去Animal类中寻找bark(),因为找不到,因而编译错误。

public class JavaOverrideOverload {
    public static class Animal {
        public void move() {
            System.out.println("动物可以移动");
        }
    }

    public static class Dog extends Animal {
        public void move() {
            System.out.println("狗可以跑和走");
        }

        public void bark() {
            System.out.println("狗可以吠叫");
        }
    }

    public static void main(String args[]) {
        Animal a = new Animal(); // Animal 对象
        Animal b = new Dog(); // Dog 对象
        Dog c = new Dog();
        a.move();// 执行 Animal 类的方法
        b.move();// 执行 Dog 类的方法
        b.bark();
        c.bark();

    }

}

 

相关文章:

  • 2022-12-23
  • 2021-10-07
  • 2021-08-06
  • 2022-03-04
  • 2022-02-12
  • 2021-12-31
  • 2021-11-20
  • 2021-09-11
猜你喜欢
  • 2021-08-30
  • 2021-08-17
  • 2021-04-09
  • 2021-12-02
  • 2021-11-03
  • 2022-03-09
  • 2022-12-23
相关资源
相似解决方案