Bài tập Java OOP: tạo lớp Date để biểu diễn ngày giờ theo yêu cầu | Codelearn

  • TuanLQ7
  • Easy
  • 100 Points

Task

Create Date class with the following information:

Explanation:

  • day, month, year are attributes describing the day, month and year of the Date objective.
  • Date(day: int, month: int, year: int) constructor parameter is used to initialize values to attributes.
  • setDate(day: int, month: int, year: int) method is used to change the values of attributes.
  • display() method displays the time information of objective in the following format "dd/MM/yyyy". For example:
    • If day = 1, month = 7, year = 1997 and when we call the display() method, the text "01/07/1997" will display on the screen.
    • If day = 8, month = 12, year = 2003 and when we call the display() method, the text "08/12/1997" will display on the screen.
  • Other methods are setter and getter.
  • To simplify, all values of the day, month and date of the Date class are considered to be valid.

A program to test the above Date class:

public class Entry {
	public static void main(String[] args) {
		Date d = new Date(1, 1, 1997);
		d.display();
		d.setDate(12, 12, 2004);
		d.display();
		d.setMonth(3);
		d.display();
	}
}

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

01/01/1997
12/12/2004
12/03/2004

Instruction

You need to create a Date class as below:

class Date {
	private int day;
	private int month;
	private int year;

	public Date(int day, int month, int year) {
		this.day = day;
		this.month = month;
		this.year = year;
	}

	public void setDate(int day, int month, int year) {
		this.day = day;
		this.month = month;
		this.year = year;
	}

	public int getDay() {
		return day;
	}

	public void setDay(int day) {
		this.day = day;
	}

	public int getMonth() {
		return month;
	}

	public void setMonth(int month) {
		this.month = month;
	}

	public int getYear() {
		return year;
	}

	public void setYear(int year) {
		this.year = year;
	}

	public void display() {
		String day = this.day + "";
		String month = this.month + "";
		String year = this.year + "";
		if (day.length() == 1) {
			day = "0" + day;			
		}
		if (month.length() == 1) {
			month = "0" + month;			
		}
		System.out.println(day + "/" + month + "/" + year);
	}
}