抽象类数组 [英] Array of abstract class

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

问题描述

为什么我不能实例化一个抽象类,而是创建一个抽象类的数组?

公共抽象类游戏{...}游戏游戏 = 新游戏();//错误游戏[] gamesArray = 新游戏[10];//没有错误

解决方案

Game[] gamesArray = new Game[10];

实例化意味着创建一个类的实例.在上面的场景中,您刚刚声明了一个 Game 类型的 gamesArray,大小为 10(只是引用,没有别的).这就是为什么它不会抛出任何错误.

尝试执行时会出现错误

gamesArray[0] = new Game();//因为抽象类不能被实例化

<小时><块引用>

但是创建一个抽象类的数组?

以后,你可以做这样的事情

gamesArray[0] = new NonAbstractGame();//其中 NonAbstractGame 扩展了 Games 抽象类.

这是非常允许的,这就是您首先要进入抽象类的原因.

Why can I not instantiate an abstract class but make an array of the abstract class?

public abstract class Game{
  ...
}

Game games = new Game(); //Error
Game[] gamesArray = new Game[10]; //No Error

解决方案

Game[] gamesArray = new Game[10];

Instantiation means creation of an instance of a class. In the above scenario, you've just declared a gamesArray of type Game with the size 10(just the references and nothing else). That's why its not throwing any error.

You'll get the error when you try to do

gamesArray[0] = new Game(); // because abstract class cannot be instantiated


but make an array of the abstract class?

Later on, you can do something like this

gamesArray[0] = new NonAbstractGame(); // where NonAbstractGame extends the Games abstract class.

This is very much allowed and this is why you'll be going in for an abstract class on the first place.

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

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