0

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);
   }
}
3
  • 4
    Please post cow, wolf and mammal. Also, note that by convention Java class names start with a capital letter. Commented Mar 8, 2015 at 21:54
  • 2
    ...and fields start with a lower and continue with camelCasing; basically the opposite of what you have. Commented Mar 8, 2015 at 21:58
  • @JSobo if you need anymore explanation I can explain it for you :) Commented Mar 8, 2015 at 22:09

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for showing me the proper conventional method of writing Java class names! Sorry for not posting the other classes, I had them exactly like you described. Thanks for the help.
@JSobo: if answer working for u, dont forgot to accept answer, this will help to future visitors.
1

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"

1 Comment

I can't believe that I missed that silly mistake. Wolf subclass wasn't extending Mammal. Thanks for pointing out my rookie mistake, also thanks for reminding me to post my other classes, will do so in the future.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.