Java reason: actual and formal argument lists differ in length
I need help creating a setter method for my code. I've created two setter methods for both string values, but I'm A) not sure if they are implemented correctly and B) not sure how to call them so that they appear on the screen. Basically, I would like to just name the lion and hippo classes and they already have a name and size, and they don't need to execute them inside my main function directly by inserting something like Hippo h = new Hippo ("Tom", " 42 ")
package game2;
public class Game2 {
public static void main(String[] args) {
//I am getting the error here, what I want to do is figure out how to
//get this to work and then declare a name and size for the animal
Hippo h = new Hippo();
Lion l = new Lion();
}
}
package game2;
public abstract class Animal {
private String name;
private String Size;
public String getName() {
return name;
}
public String getSize() {
return Size;
}
public void setName(String name) {
name = "Tom";
}
public void setSize(String name) {
name = "42";
}
public Animal(String theName, String theSize) {
name = theName;
Size = theSize;
}
}
package game2;
public class Hippo extends Animal {
public Hippo(String name, String Size) {
super(name, Size);
}
}
package game2;
public class Lion extends Animal{
public Lion(String name, String Size) {
super(name, Size);
}
}
source to share
Remember, when you create a constructor yourself, you are overloading the default constructor. Therefore, you need to pass two arguments.
You didn't pass arguments to constructors when instantiating:
Hippo h = new Hippo();
Lion l = new Lion();
Since your class constructors expect two parameters.
public Hippo(String name, String Size) {
super(name, Size);
}
and
public Lion(String name, String Size) {
super(name, Size);
}
Solutions:
Alternatively, you can pass arguments when creating objects:
Hippo h = new Hippo("name", "33");
Lion l = new Lion("name", "22");
Or you need to implement overloaded constructors for these.
source to share
If you want to define the name and size after creating your animal, you need a parameterless constructor. Currently all constructors require you to pass 2 arguments. So write one!
Here's an example:
public Hippo() {
setSize(insert default size here);
setName(insert default name here);
}
Then you can create a hippo:
Hippo hippo = new Hippo();
hippo.setName("Tom");
source to share