Bài tập Java OOP: tạo các setter và getter | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create a Student class with the following information:

Explanation:

  • id, name, age, address, score attributes describe the ID, name, age, address and score respectively of a student where the score is guaranteed to be greater than 0 and less than or equal to 10 (if score < 0, assign 0 to score, if score > 10, assign 10 to score).
  • Student() is the no-arg constructor.
  • Student(id: int, name: String, age: int, adderss: String, score: int) constructor parameter is used to initialize values to the following attributes id, name, age, address, score
  • The other methods are setter and getter.

A program to test the above Student class:

public class Entry {
	public static void main(String[] args) {
		Student s = new Student(1001, "Trung", 24, "Ha Noi", 5);
		System.out.println(s.getId());
		System.out.println(s.getName());
		System.out.println(s.getAge());
		System.out.println(s.getAddress());
		System.out.println(s.getScore());
		s.setScore(-7);
		System.out.println(s.getScore());
		s.setScore(15);
		System.out.println(s.getScore());
	}
}

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

1001
Trung
24
Ha Noi
5
0
10

Instruction

You need to create a Student class as below:

public class Student {
	private int id;
	private String name;
	private int age;
	private String address;
	private int score;

	public Student() {

	}

	public Student(int id, String name, int age, String address, int score) {
		this.id = id;
		this.name = name;
		this.age = age;
		this.address = address;
		this.setScore(score);
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		if (score < 0) {
			this.score = 0;
		} else if (score > 10) {
			this.score = 10;
		} else {
			this.score = score;
		}
	}
}