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

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

问题描述

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

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];

实例化意味着创建类的实例。在上面的场景中,您刚刚声明了 gamesArray 类型游戏,其大小为 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天全站免登陆