Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 953
Nitin Avatar asked Oct 11 '13 05:10

Nitin


3 Answers

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.

like image 102
Rahul Avatar answered Oct 11 '22 16:10

Rahul


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.

like image 25
Dawood ibn Kareem Avatar answered Oct 11 '22 16:10

Dawood ibn Kareem


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.

like image 36
user2339071 Avatar answered Oct 11 '22 16:10

user2339071