Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
96 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...