动态方法分派在Java中如何工作 [英] How does dynamic method dispatching work in Java

查看:73
本文介绍了动态方法分派在Java中如何工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

超类变量可以访问子类的重写方法吗? 例如:

Can a superclass variable access an overridden method of a subclass. For ex:

class A {
    void callMe() {
        System.out.println("Inside A");
    }
}

class B extends A {
    void callMe() {
        System.out.println("Inside B");
    }
}

class Dispatch {
    public static void main(String args[]) {
        A a = new A();
        B b = new B(); // Object of type B
        A r; // Obtain a reference of type A

        r = a; // Refers to A object
        r.callMe(); // Calls A's version of callMe()

        r = b; // Refers to B object
        r.callMe(); // calls B's version of callMe() and my question is on this
    }
}

我早些时候了解到,引用子类对象的超类变量只能访问由超类定义的对象的那些部分.那么第二个r.callMe()如何调用BcallMe()版本?它应该只再次调用AcallMe()版本.

I learned earlier that a superclass variable that is referencing a subclass object can access only those parts of an object that are defined by the superclass. Then how can the second r.callMe() call B's version of callMe()? It should only call A's version of callMe() again.

推荐答案

您的问题

r = b;

r=b;

现在r捕获"new B()"对象.当您调用r.callme()时,请在B类中运行callme方法.因为r有B对象.

now r catch "new B()" object.When u call r.callme() then run callme method in B class. Because r has B object.

由于超类的引用类型没有子类名称的方法,因此任何程序都会引发编译时错误.

Any program will throw a compile time error since reference type of super class doesn't have a method by the name of sub class.

例如

class Animal {
  public void move() {
     System.out.println("Animals can move");
  }
}

class Dog extends Animal {
  public void move() {
     System.out.println("Dogs can walk and run");
  }

  public void bark() {
     System.out.println("Dogs can bark");
  }
 }

 public class TestDog {

  public static void main(String args[]) {
    Animal a = new Animal();   // Animal reference and object
    Animal b = new Dog();   // Animal reference but Dog object

    a.move();   // runs the method in Animal class
    b.move();   // runs the method in Dog class
    b.bark();
 }
}

输出

TestDog.java:26: error: cannot find symbol
  b.bark();
   ^
 symbol:   method bark()
 location: variable b of type Animal
 1 error

这篇关于动态方法分派在Java中如何工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆