Search code examples
javaabstract-class

Can we create an object from an abstract class?


How does this work since we can not create an object from an abstract class? In this class I have declared an Alien array, and Alien class is an abstract class. How does the creation work in the constructor?

public class AlienPack {

    private  Alien[] aliens;  //composition 

    //cons with para of array size 
    public AlienPack(int numAliens) {
        aliens = new Alien [numAliens]; //how can we create objects from AC????????????
    }

    public void addAlien(Alien newAlien, int index) {
        aliens[index] = newAlien;
    }

    public Alien[] getAliens() {
        return aliens;
    }

    public int calculateDamage() {
        int damage = 0;
        for (int i=0; i<aliens.length; i++)            // Call getDamage() from each alien to
            damage += aliens[i].getDamage();             // calculate total damage??????????????????????????
        return damage;
    }
}

Solution

  • The key distinction is that you created a variable of type Alien[]. Think of this as the place to store any Aliens that you might create. You haven't tried to create any to store there with something like:

    1. Alien a = new Alien();
    2. aliens[0] = a;
    

    And this is where an error will get thrown. The right side of the = is where the object gets "created" on line 1. (Although it can't be created because it's abstract) The left side is where a reference variable a is created to store an Alien.Which would be fine on its own, as in your case. Abstract / Interface type variables are fine on their own, we can then store concrete implementations of those Abstract / Interface types in those variables.