Lee Lee - 8 days ago 8
Java Question

How to call a constructor within a second constructor?

I have been instructed to:


  • Create a second Parrot constructor which takes an Integer as its only argument.

  • Call the other constructor providing "Polly" as the name, and the Integer argument as the age.



Within this method:

public class Parrot extends Omnivore
{

Parrot()
{
name = "Billy";
age = 6;
noise = "Argh!";
}
Parrot(int i)
{
i = age;
//Call other constructor providing "Polly" as name?

}

}


I'm a little confused on how to do this, I've never really came across calling multiple constructors before so any help on how this would be done would be much appreciated, thanks.

Answer

Step one, make a constructor that takes a String and an int.

Parrot(String name, int age)   
{
    this.age = age;
    this.name = name;
} 

Step two, call that constructor with a hardcoded default name and an age provided. Use this. Like

Parrot(int i)   
{
    this("Polly", i);
}