Home Tutorial Java Core Implementation of Day Class

 
 

Share on Google+Share on Google+
Implementation of Day Class
Posted on: June 16, 2010 at 12:00 AM
Advertisement
In this section, you will learn how to implement Day class.

Implementation of Day Class

Here we are going to design and implement the class Day. The class Day should store the days of the week. Then test the following operations through the object of the class Day:
1) Set the day.
2) Print the day.
3) Return the day.
4) Return the next day.
5) Return the previous day.
6) Calculate and return the day by adding certain days to the current day.For example, if the current day is Monday and we add four days, the day to be returned is Friday. similarly, if today is Tuesday and we add 13 days, the day to be returned is Monday.

Here is the code:

public class Day {
	final static int SUNDAY = 0;
	final static int MONDAY = 1;
	final static int TUESDAY = 2;
	final static int WEDNESDAY = 3;
	final static int THURSDAY = 4;
	final static int FRIDAY = 5;
	final static int SATURDAY = 6;

	private int day;

	public Day(int day) {
		this.day = day;
	}

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

	public int getDay() {
		return day;
	}

	public void print() {
		System.out.println(this.toString());
	}

	public int nextDay() {
		int next;
		next = day + 1;
		return next;
	}

	public int previousDay() {
		int prevDay;
		prevDay = day - 1;
		return prevDay;
	}

	public int addDays(int days) {
		return (day + days) % 7;
	}

	public String toString() {
		switch (this.day) {
		case SUNDAY:
			return "Sunday";
		case MONDAY:
			return "Monday";
		case TUESDAY:
			return "Tuesday";
		case WEDNESDAY:
			return "Wednesday";
		case THURSDAY:
			return "Thursday";
		case FRIDAY:
			return "Friday";
		case SATURDAY:
			return "Saturday";
		}
		return "";
	}

	public static void main(String[] args) {
		System.out.println("******Test Day******");
		System.out.println();
		System.out.print("Set day: ");
		Day d = new Day(SUNDAY);
		d.print();
		System.out.print("Next day: ");
		d.setDay(d.nextDay());
		d.print();
		System.out.print("Previous day: ");
		d.setDay(d.previousDay());
		d.print();
		System.out.print("After 5 days: ");
		d.setDay(d.addDays(5));
		d.print();
	}
}

Output:

*******Test Day*******

Set day: Sunday
Next day: Monday
Previous Day: Sunday
After 5 days: Friday

Advertisement

Related Tags for Implementation of Day Class:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: June 16, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com