多态性和参数?

Polymorphism and Parameters?

所以我知道由于多态性,允许这样做: 超类 Apt = new Subclass(); 但我想知道以下情况:

Superclass Abc = new Subclass(); 
do(Abc);
void doThat(Superclass Abc)
   Abc.Ball();

所以在方法 doThat 中的 Abc.method 调用中,这是调用超类的 Ball 方法还是调用子类的 Ball 方法(假设子类有覆盖了 Ball 方法)。如果它确实调用了 Subclass 的重写 Ball 方法,为什么我们不能将方法 doThat 改为:void doThat(Subclass Abc)。感谢您的帮助,如果它没有意义,我会澄清更多。

如果 Ball 方法是静态的,它将调用超级 class,因为 Ball 方法是在 class 级别定义的,而如果它是在对象级别定义的,那么它肯定会在 sub class.

上调用重写的方法

在您描述的情况下,调用

Abc.Ball();

将调用 Subclass 中的实现。

它正在调用重写方法所针对的重写方法。

void doThat(Subclass Abc)

如果你在这里使用Subclass你只能将子类实例传递给它。相反,如果你有

void doThat(Superclass Abc)

然后你可以传递任何实现了Superclass的对象,这就是多态性的来源。 doThat 方法接受多种类型的对象,唯一的要求是它应该实现超类。

如果我进一步解释, 假设您有两个名为 Subclass1Subclass2 的子类,它们是超类的实现,其中超类是一个接口。 (这些子类应该实现超类方法定义,因此两个子类都有 ball 方法)

然后无论实例到达doThat方法,它都会调用相应对象的ball方法。作为 void doThat(Superclass Abc) 接受超类类型。

does this make a call to the Ball method of the Superclass or does it make a call to the Ball method of the Subclass

调用Abc.Ball()会调用子类中重写的方法

If it does make a call to the overridden Ball method of the Subclass, why can we just not make the method doThat be: void doThat(Subclass Abc) instead

假设您有两个 Superclass 的子类:

Superclass abc = new SubclassA();
Superclass xyz = new SubclassZ();

定义void doThat(Superclass abc) 意味着方法doThat() 将接受作为Superclass 或其任何子类的实例的任何对象。然后你可以做 doThat(abc)doThat(xyz) 并且两者都会在适当的实例中调用 Ball() 方法。

相比之下,如果您有 doThat(SubclassA abc),您还需要为 Superclass 的每个子类指定一个特定的方法,例如 doThat(SubclassZ xyz).