首页 > 代码库 > Java中Animal b = new Dog();Dog c = new Dog();的区别
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(); } }
Java中Animal b = new Dog();Dog c = new Dog();的区别
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。