zoukankan      html  css  js  c++  java
  • 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();
    
        }
    
    }
  • 相关阅读:
    异象石(引理证明)
    Codeforces Round #664 (Div. 2)
    2020 年百度之星·程序设计大赛
    Codeforces Round #663 (Div. 2)
    Codeforces Round #662 (Div. 2)
    相等运算符
    Unicode编码
    算术运算符
    强制类型转换到Boolean
    强制类型转换到Number
  • 原文地址:https://www.cnblogs.com/guweiwei/p/6288024.html
Copyright © 2011-2022 走看看