Nạp chồng phương thức khởi tạo trong Java | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Student class with the following information:

Explanation:

  • name and gender are two private attributes of Student class.
  • Student() is the no-arg constructor which is used for initializing 2 values: name = "Unknown", gender = 'u'
  • Student(name: String) is the parameter constructor which is used for initializing values to 2 attributes name and gender (this.name = name; gender = 'u').
  • Student(gender: char) is the parameter constructor which is used for initializing values to 2 attributes gender and name (this.gender = gender, name = "Unknown").
  • Student(name: String, gender: char) is the parameter constructor which is used for initializing values to 2 attributes name and gender.
  • display() method is used for displaying information of an object on the screen. If gender = 'm', display "Gender: Male" on the screen, if gender = 'f', display "Gender: Female" on the screen, if gender = 'u', display "Gender: Unknown" on the screen. See the example below:
    • If name = "Thu", gender = 'f', when we call the display() method, the screen will display as below:
      Name: Thu
      Gender: Female​
    • If name = "Sang", gender = 'u', when we call the display() method, the screen will display as below:
      Name: Sang
      Gender: Unknown
    • If name = "Unknown", gender = 'u', when we call the display() method, the screen will display as below:
      Name: Unknown
      Gender: Unknown​

A program to test the above Student class:

public class Entry {
	public static void main(String[] args) {
		Student s1 = new Student();
		s1.display();
		Student s2 = new Student("Quang");
		s2.display();
		Student s3 = new Student('m');
		s3.display();
		Student s4 = new Student("Thu", 'f');
		s4.display();
	}
}

When the above code is compiled and executed, it produces the following result:

Name: Unknown
Gender: Unknown
Name: Quang
Gender: Unknown
Name: Unknown
Gender: Male
Name: Thu
Gender: Female

Instruction

You need to create a Student class as below:

public class Student {
	private String name;
	private char gender;

	public Student() {
		name = "Unknown";
		gender = 'u';
	}

	public Student(String name) {
		this.name = name;
		this.gender = 'u';
	}

	public Student(char gender) {
		this.name = "Unknown";
		this.gender = gender;
	}

	public Student(String name, char gender) {
		this.name = name;
		this.gender = gender;
	}

	public void display() {
		System.out.println("Name: " + name);
		if (gender == 'u') {
			System.out.println("Gender: Unknown");
		}
		if (gender == 'm') {
			System.out.println("Gender: Male");
		}
		if (gender == 'f') {
			System.out.println("Gender: Female");
		}
	}
}