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.
Because when you make an array of some object type, you're not trying to instantiate the objects. All you're making is a number of slots to put references in.
new Game[10];
makes 10 slots for Game
references, but it doesn't make a single Game
.
Because you don't violate the abstract class
rules.Essentially,
Game games = new Game();
is broken down to:
Game games; //Will Work because it's just a declaration
games=new Game(); //Will not work because it's instantiation
While creating objects is perfectly valid for abstract classes, initializing is not permitted.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With