何时使用抽象类作为类型 [英] When to use abstract class as type

查看:80
本文介绍了何时使用抽象类作为类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,在尝试理解抽象类时,我仍然对一件事感到困惑.您何时想声明其抽象类的对象类型.例如

So while trying to understand abstract classes, there is still one thing I am confused on. When do you ever want to declare an object type of its abstract class. For example

public abstract class GameObject
{
 public abstract void draw();
 public static void main(String[] args)
 {
 GameObject player = new Player();
 Menu menu = new Menu();
 }

}
public class Player extends GameObject
{
 override 
 public void draw()
 {
 // Something
 }

}
public class Menu extends GameObject
{
 override 
 public void draw()
 {
 // Something
 }
}

通常,我只是实例化一个玩家类型的玩家对象.但是,我已经看到抽象类用作新对象的变量类型.您何时会选择执行此操作?谢谢!

Normally, I would just instaniate a player object of player type. However, I have seen abstract classes used as the variable type of the new object. When would you ever choose to do this? Thanks!

推荐答案

每次需要将变量作为抽象类的实例时,您都会这样做,但实际上并不关心具体类型是什么(并且不希望其余代码假定使用了特定的子类).例如:

You would do that every time you need the variable to be an instance of the abstract class, but don't really care about what the concrete type is (and don't want the rest of the code to assume a specific subclass is used). For example:

GameObject[] gameObjects = new GameObject[] {new Menu(), new Player()};
drawAll(gameObjects);

...

private void drawAll(GameObject[] gameObjects) {
    for (GameObject gameObject : gameObjects) {
        gameObject.draw();
    }
}

抽象类型通常用作返回类型(因为您不希望调用者知道返回的具体类型:它可能会在以后更改,或者可能会根据配置的参数而有所不同).

The abstract type is often used as a return type (because you don't want the caller to know what concrete type is returned: it could change later, or could vary based on the arguments of the configuration).

它也经常用作方法参数类型,以便该方法可以接受抽象类型的任何子类的参数并进行多态使用.

It's also often used as method parameter type, so that the method can accept an argument of any subclass of the abstract type and use it polymorphically.

当然,作为数组/集合类型,它能够将多个子类的实例存储在唯一的集合中.

And of course, as an array/collection type, to be able to store instances of multiple subclasses in a unique collection.

这篇关于何时使用抽象类作为类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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