Nitin Nitin - 4 years ago 119
Java Question

Array of abstract class

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

Answer Source
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 Games(); // 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 NonAbstractGames(); // where NonAbstractGames 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download