问题描述
我是Java初学者.我了解类继承的概念,但是有一件事我不太了解.我正在阅读Java for Dummies,它正在解释多态.它以以下代码为例:
I'm a Java beginner. I understand the concepts of class inheritance, but there's one thing I don't quite understand. I'm reading through Java for Dummies, and it's explaining polymorphism. It gives this code as an example:
class Player {
public void move() {...
class BetterPlayer extends Player {
public void move() {...
public class TicTacToeApp {
public static void main(String[] args) {
Player p1 = new Player();
Player p2 = new BetterPlayer();
playTheGame(p1, p2);
}
public static void playTheGame(Player p1, Player p2) {
p1.move();
p2.move();
}
}
为什么将p2创建为Player对象?这是我的理解:
Why was p2 created as a Player object? Here's my understanding:
如果p2是BetterPlayer对象(这样声明:BetterPlayer p2 =新的BetterPlayer ...):
-upcasting是自动的,因此仍然可以使用playTheGame方法
-p2可以用于需要BetterPlayer对象的任何方法
If p2 were a BetterPlayer object (declared like this: BetterPlayer p2 = new BetterPlayer...):
-upcasting is automatic, so it would still work with the playTheGame method
-p2 can be used by any methods requiring a BetterPlayer object
但是因为它是作为Player对象创建的,所以现在只要有需要BetterPlayer对象的方法使用p2,就必须将其显式转换为BetterPlayer对象,对吗?这似乎是更多的工作,没有任何好处,所以我猜想这样做一定会有好处.是什么?
But since it was created as a Player object, now any time p2 is used by a method requiring a BetterPlayer object, it must be explicitly cast to a BetterPlayer object, right? That seems like more work with no benefit, so I'm guessing there has to be some benefit to doing it that way; what is it?
推荐答案
未将变量p2创建为Player对象.它是指向BetterPlayer对象的参考.
The variable p2 was not created as a Player object. It's a reference that points to a BetterPlayer object.
无论将p2声明为Player引用还是BetterPlayer引用,都可以将其用作Player引用.
Regardless whether p2 is declared as a Player or BetterPlayer reference, it can be used as a Player reference.
将其声明为Player的一个优点是,可以防止您耦合仅与BetterPlayer一起使用的任何代码,并在以后保留将代码用于另一个子类选项(例如BestPlayer)的可能性.
An advantage of declaring it as a Player is that you are prevented from coupling any code that works only with BetterPlayer, keeping open the option of using the code for another subclass option in the future -- e.g., BestPlayer.
这篇关于声明一种类型的对象和另一种类型的对象有什么好处?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!