首页 > 解决方案 > 多态性:在不知道对象的完整类的情况下一致地请求行为

问题描述

我试图理解多态性的概念。我无法理解下面的句子:

我们可以在不知道对象的完整类的情况下一致地请求行为

本书展示了一个示例代码,显示了三个类,然后创建超类的引用,然后使用该引用调用派生类方法,这是实现多态性的常用技术,如下所示:

class B extends A{
void callme(){
System.out.println(“Inside B’s callme method”);
  }
}  //Q. What can you say about callme( )?
class C extends A {
void callme(){
System.out.println(“Inside C’s callme method”);
  }
}
class Dispatch {
public static void main(String args[ ]) {   
A a = new A(); //obj of Type A
B b = new B(); //obj of Type B
C c  = new C(); //obj of Type C
A r;
r = a; // r refers to an A object
r.callme();

r = b;//r refers to a B object
r.callme();  
r = c;// r refers to a C object
r.callme();
  }
}

有人请指导我“为什么我们说我们没有关于整个对象类别的信息”?构造函数可以告诉我们这个类。这里还列出了所有的类。什么是真实的场景?

标签: polymorphism

解决方案


让我们举一个例子,其中泛型类名 A、B 和 C 更“真实”:

public class Dispatcher {
    public static void main(String[] args) {
        Animal a = new Animal();
        Animal b = new Dog();
        Animal c = new Cat();

        a.makeSound(); // prints "Generic animal sound"
        b.makeSound(); // prints "Woof!"
        c.makeSound(); // prints "Meow~~"

        //b.chaseBall() wouldn't work
        //c.purr() wouldn't work
    }


    static class Animal {
        public void makeSound() {
            System.out.println("Generic animal sound");
        }
    }

    static class Dog extends Animal {
        @Override
        public void makeSound() {
            System.out.println("Woof!");
        }

        public void chaseBall() {
            System.out.println("*goes chasing the ball*");
        }
    }

    static class Cat extends Animal {
        @Override
        public void makeSound() {
            System.out.println("Meow~~");
        }

        public void purr() {
            System.out.println("purrrrrr");
        }
    }
}

在 main 方法的第一行中,声明了三个变量,它们都是 Animal 类型,尽管第二个实际上是 Dog 类型,第三个是 Cat 类型。但是由于它们现在被声明为动物类型,因此所有已知信息:它们是动物。

这就是为什么对所有这些对象调用 makeSound() 有效的原因:我们可以一致地请求(动物的)行为,而无需知道对象的完整类(如狗或猫)。

但是由于 b (a Dog) 和 c (a Cat) 现在被声明为动物,它们不能拥有与这些类型相对应的方法调用(例如,chasseBall() 和 purr())。


推荐阅读