I want to change the default constructor (person1) from public to private and then ask the user to input the information instead of the given values.
I have two different classes - Person; which is encapsulated and then PersonTest which tests the information.
class Person {
// Data Members
private String name; // The name of this person
private int age; // The age of this person
private char gender; // The gender of this person
// Default constructor
public Person() {
name = "Not Given";
age = 0;
gender = 'U';
}
// Constructs a new Person with passed name, age, and gender parameters.
public Person(String personName, int personAge, char personGender) {
name = personName;
age = personAge;
gender = personGender;
}
// Returns the age of this person.
public int getAge( ) {
return age;
}
// Returns the gender of this person.
public char getGender( ) {
return gender;
}
// Returns the name of this person.
public String getName( ) {
return name;
}
// Sets the age of this person.
public void setAge( int personAge ) {
age = personAge;
}
// Sets the gender of this person.
public void setGender( char personGender ) {
gender = personGender;
}
// Sets the name of this person.
public void setName( String personName ) {
name = personName;
}
}
import java.util.Scanner;
public class PersonTest {
// Main method
public static void main(String[] args){
// Create first instance of Person class to test the default constructor.
Person person1 = new Person();
// Create a new instance of the Person class.
Person person2 = new Person();
Scanner input = new Scanner(System.in);
// Get the values from user for first instance of Person class.
System.out.println("Person 2 Name: ");
person2.setName(input.nextLine());
System.out.println("Person 2 Age: ");
person2.setAge(input.nextInt());
System.out.println("Person 2 Gender: ");
person2.setGender(input.next().charAt(0));
// Print out the information.
System.out.println("Person 1 Name = " + person1.getName());
System.out.println("Person 1 Age = " + person1.getAge());
System.out.println("Person 1 Gender = " + person1.getGender());
System.out.println("");
System.out.println("Person 2 Name = " + person2.getName());
System.out.println("Person 2 Age = " + person2.getAge());
System.out.println("Person 2 Gender = " + person2.getGender());
System.out.println("");
}
}