Java 如何在第二个构造函数中调用构造函数?
我奉命:Java 如何在第二个构造函数中调用构造函数?,java,constructor,Java,Constructor,我奉命: 创建第二个Parrot构造函数,该构造函数将整数作为其唯一参数 调用另一个构造函数,提供“Polly”作为名称,整数参数作为年龄 在此方法中: public class Parrot extends Omnivore { Parrot() { name = "Billy"; age = 6; noise = "Argh!"; } Parrot(int i) { i = age; //Call other const
- 创建第二个Parrot构造函数,该构造函数将整数作为其唯一参数
- 调用另一个构造函数,提供“Polly”作为名称,整数参数作为年龄
public class Parrot extends Omnivore
{
Parrot()
{
name = "Billy";
age = 6;
noise = "Argh!";
}
Parrot(int i)
{
i = age;
//Call other constructor providing "Polly" as name?
}
}
我对如何实现这一点有点困惑,我以前从未真正遇到调用多个构造函数的情况,因此非常感谢您提供有关如何实现这一点的任何帮助。第一步,创建一个包含
字符串和int
的构造函数
Parrot(String name, int age)
{
this.age = age;
this.name = name;
}
第二步,使用硬编码的默认值名称
和提供的年龄
调用该构造函数。使用此
。像
Parrot(int i)
{
this("Polly", i);
}
当我们希望在一个构造函数中执行多个任务而不是在一个构造函数中为每个任务创建代码时,可以使用此过程。我们为每个任务创建一个单独的构造函数,并使其链更具可读性
使用此方法,您可以
让我们看看类Temp示例
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}
public static void main(String args[])
{
// invokes default constructor first
new Temp();
}
}
问题的一部分在于,您没有一个构造函数可以接受“Polly”
。很简单:您不能,只在this()的第一行。此外,所有其他方法都与您的问题无关。所以请不要包括它们。