JSobo
JSobo

Reputation: 1

Adding subclasses into a superclass array in Java

I want to initialize a couple of subclasses and put them all into an array of the superclass mammal. With this code I get the error: no suitable method found for add(wolf). I have no idea what I'm doing wrong, any help is appreciated.

class gameRunner{
   cow Cow = new cow();
   wolf Wolf = new wolf();
   ArrayList<mammal> mammalArray = new ArrayList<mammal>();

   public gameRunner(){
     mammalArray.add(Cow);
     mammalArray.add(Wolf);
   }
}

Upvotes: 0

Views: 4322

Answers (2)

Kebab Programmer
Kebab Programmer

Reputation: 1219

Basically to create those classes you firstly need to have a Mammal Class

For me id work with this

public abstract class Mammal{

  //Constructor
  //Getters and Setters
}

then to create the subclasses you would have

public Cow extends Mammal{
  //Constructor
  //Getters and Setters
}

and

public Wolf extends Mammal{
  //Constructor
  //Getters and Setters
}

So that in my main class I can then create an arraylist which can hold both objects without compiler errors

class gameRunner{
   Cow cow = new Cow();
   Wolf wolf = new Wolf();
   ArrayList<Mammal> mammalArray = new ArrayList<Mammal>();

  public gameRunner(){
      mammalArray.add(cow);
      mammalArray.add(wolf);
   }
 }

Why I have the Mammal class is that you cannot instantiate an abstract class, but you can instantiate it's subclasses and the subclasses can inherit methods from the superclass

Hope this helped :)

Upvotes: 5

auracool
auracool

Reputation: 172

It is pretty difficult to tell without seeing other classes but try this:

Since cow seems to be fine I guess that you have extended mammal from the cow class...so Ensure that wolf extends mammal that error to me is saying "Hey i can't add a wolf to this mammal array! wolf isn't even a type of mammal...so go check it extends mammal pal"

Upvotes: 1

Related Questions