Java中Animal b = new Dog();Dog c = new Dog();的区别

由于在编译阶段,只是检查参数的引用类型。然而在运行时,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();

    }

}

 

posted @ 2017-01-15 22:38  暖阳g  阅读(4324)  评论(0编辑  收藏  举报