Add 3 constructors to the Person class from the last task, use constructor chaining to reuse code:
-
The first should take no arguments and produce a person with name “No name” and age = 1.
-
The second should accept only an integer number for the age and produce a person with name “No name” and age equal to the passed parameter.
-
The third one should accept a string for the name and an integer for the age and should produce a person with the given name and age.
Add the following code to your main method :
public static void main(String[] args) throws Exception {
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(isr);
Class personClass = Class.forName("Person");
Constructor emptyCtor = personClass.getDeclaredConstructor();
Constructor ageCtor = personClass.getDeclaredConstructor(int.class);
Constructor nameAgeCtor = personClass
.getDeclaredConstructor(String.class, int.class);
String name = reader.readLine();
int age = Integer.parseInt(reader.readLine());
Person basePerson = (Person) emptyCtor.newInstance();
Person personWithAge = (Person) ageCtor.newInstance(age);
Person personFull = (Person) nameAgeCtor.newInstance(name, age);
System.out.printf("%s %s%n", basePerson.name, basePerson.age);
System.out.printf("%s %s%n", personWithAge.name, personWithAge.age);
System.out.printf("%s %s%n", personFull.name, personFull.age);
}
If you defined the constructors correctly, the test should pass.