Java原因:实际参数和形式参数列表的长度不同 [英] java reason: actual and formal argument lists differ in length
问题描述
我需要帮助为我的代码创建一个setter方法.我为我的两个字符串值都创建了两个setter方法,但是我(A)不知道它们的实现是否正确,并且B)不知道如何调用它们以便它们出现在屏幕上.本质上,我希望能够仅调用我的lion和hippo类,并让它们具有名称和大小,而不必通过在主函数中直接插入类似的代码来实现它们河马h =新河马(汤姆","42")
I need help creating a setter method for my code. I have created two setter methods for both of my string values, but I am A) not sure if they are implemented correct, and B) not sure how to call them so that they appear on the screen. Essentially I would like to be able to just call my lion and hippo classes and have them already have a name and a size, and not have to implement 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);
}
}
推荐答案
请记住,当您自己实现构造函数时,您会重载默认的构造函数.因此,您需要传递两个参数.
Remember when implement constructor by your own, you are overload the default constructor. So you need to pass two arguments.
实例化时,您没有传递构造函数的参数:
You didnot pass the arguments for constructors when you instantiate:
Hippo h = new Hippo();
Lion l = new Lion();
因为您的类构造函数需要两个参数.
Because your class constructors expect two parameters.
public Hippo(String name, String Size) {
super(name, Size);
}
并且:
public Lion(String name, String Size) {
super(name, Size);
}
解决方案:
在实例化对象时,您都可以传递参数:
Either you can pass arguments when you instantiating objects:
Hippo h = new Hippo("name", "33");
Lion l = new Lion("name", "22");
或者您需要为此实现重载的构造函数.
Or you need to implement overloaded constructors for these.
这篇关于Java原因:实际参数和形式参数列表的长度不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!