Question

In: Computer Science

The Date Class This class will function similarly in spirit to the Date class in the...

The Date Class

This class will function similarly in spirit to the Date class in the text, and behaves very much like a “standard” class should. It should store a month, day, and year, in addition to providing useful functions like date reporting (toString()), date setting (constructors and getters/setters), as well as some basic error detection (for example, all month values should be between 1-12, if represented as an integer). Start this by defining a new class called “Date” or use Date.java, and implement the data items and methods listed in your “contract” below. By declaring both data and methods that will operate on this data in one file, we are “wrapping up” chunks of dedicated functionality (methods) with the data items that they operate on in one clean and simple abstraction: the Class. To test your Date class use the driver ClassDesignIIDriver.java. If you are starting from an existing Date.java, carefully read the instructions bellow to be sure that you have added all new functionality.

Class Invariants

Enforce the following “rules” that your class should never violate. By doing this you maintain the coherency of your object’s internal state – this is also known as “never invalidating the state (data) of your object”. In our Fractions homework, this would involve modifying getters/setters so as to never accept a zero denominator. Here we’ll consider some Invariants for the Date class.

  • All month values should be in between 1-12
  • All day values should be in between 1-31
  • All year values should be positive.

Data Members

Declare a variable for month, day, and year.

  • Define these as private? public?
    1. What is the difference between the public and private access modifiers?
    2. When data is defined as static...
      1. Can it be accessed or read?
      2. Can it be written to?
      3. If we had declared one static variable and 10 objects declared in RAM, how many static variables would also be in memory?
    3. When data is defined as final...
      1. Can it be accessed/used or read?
      2. Can it be written to other than the first initialization?
      3. Why would it be ok to declare a final (or static final) variable as public?
      4. Later: How does the concept of a final variable relate to Immutable classes?

Method Members

  • Provide getter/setter methods for each of the variables above
  • Provide logic in your setter methods to observe the following Class Invariants
  • public Date() {}
    • This is the default no-arg constructor.
  • public Date(int m, int d, int y);
    • Should we use month = m; or setMonth(m)? What are the differences?
  • public Date(Date other);
    • This method is a copy constructor; initialize your object’s data members (this.month, etc) using “other”.
  • public String toString(); //report on your date
  • public boolean equals(Object other);
    • In this method, you’ll compare “this” to “that”, once the other object has been checked and cast.
    • See Fraction equals() for proper null-check and casting.

Sample Output

  • a is :0.0.0
  • b is :2.1.2030
  • c is :2.1.2030
  • B and A are equal: false
  • B and C are equal: true

Solutions

Expert Solution

PLEASE GIVE IT A THUMBS UP, I SERIOUSLY NEED ONE, IF YOU NEED ANY MODIFICATION THEN LET ME KNOW, I WILL DO IT FOR YOU

Que- Define these as private? public?

Ans- Define these as private for acheaving encapsulation and data hiding and expose these variables only through getters and setters.

Que- What is difference between the public and private access modifiers?

Ans- private access modifier is accessible only within class

public access modifier is accessible everywhere means outside class also.

Que- When data is define as a static?

Ans- When we want to share particular data value with all objects then we can define data as a static.

Ex-If in a college there are 500 students and all are having same college name so in this case we can declare college

name as a static

class students

{

static String collegeName="abc";

int rollNo;

String studentName;

}

Que- a) can it be accessed or read?

Ans- Yes it can be accessed or read

Que- b)can it be written to?

Ans-Yes

Que-If we had decaler one static variable and 10 objects declare in RAM,how manny static variables would also be in a memory?

Ans-There will be only one satic variable which will be created at the time of class loading and common to all 10 objects.

Que-a) When data is define as a final.

Ans- Data can be define as a final when we dont want to modify its value after its first initialization and we want its constant value

throught program life cycle.

Que-b) Can it be written other than first initialization?

Ans- We can not change constant variable value once it initialized. If you are using blank final variable then you should initializ this variable in

constructor.

Que-c) Why would it be Ok to declare a final (or static final) variable as a public?

Ans- We can access it outside class also. It is final variable so no one can change its value so no need to keep it as a private.

Que- Later: How does the concept of a final variable relate to Immutable class?

Ans- When we need to prevent particular class from extending and when we dont want to change the attributes/variables values of particular class

at that time we should make the class immutable by using final keyword.

Que- Should we use month=m;or setMonth(m)? What are the differences?

Ans- In your case you are writing validation logic in setter method so we need to use setter method in constructor to validate fields.

but in normal case it will not be good practice to use setter method in constructor beacause one can override your methods and can change their behaiviour

class Date {
  private int day;

  private int month;

  private int year;

  // default constructor

  public Date() {
    this.day = 0;

    this.month = 0;

    this.year = 0;
  }

  // parameterize constructor

  public Date(int m, int d, int y) {
    setDay(d);

    setMonth(m);

    setYear(y);
  }

  //copy constructor

  public Date(Date other) {
    this.day = other.day;

    this.month = other.month;

    this.year = other.year;
  }

  // getters and setters

  public int getDay() {
    return day;
  }

  public void setDay(int day) {
    if (day >= 1 && day <= 31) this.day = day; else System.out.println(
      "Error: Day value should be between 1 to 31"
    );
  }

  public int getMonth() {
    return month;
  }

  public void setMonth(int month) {
    if (month >= 1 && month <= 12) this.month = month; else System.out.println(
      "Error: Month value should be between 1 to 12"
    );
  }

  public int getYear() {
    return year;
  }

  public void setYear(int year) {
    if (year >= 0) this.year = year; else System.out.println(
      "Error: Year value must have positive"
    );
  }

  @Override
  public String toString() {
    return month + "." + day + "." + year;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) return true;

    if (obj == null) return false;

    if (getClass() != obj.getClass()) return false;

    Date other = (Date) obj;

    if (day != other.day) return false;

    if (month != other.month) return false;

    if (year != other.year) return false;

    return true;
  }

  public static void main(String[] args) {
    Date a = new Date();

    Date b = new Date(2, 1, 2030);

    Date c = new Date(2, 1, 2030);

    System.out.println("a is : " + a.toString());

    System.out.println("b is : " + b.toString());

    System.out.println("b is : " + c.toString());

    System.out.println("B and A are equal : " + b.equals(a));

    System.out.println("B and C are equal : " + b.equals(c));
  }
}

Related Solutions

(Using Date Class) The following UML Class Diagram describes the java Date class: java.util.Date +Date() +Date(elapseTime:...
(Using Date Class) The following UML Class Diagram describes the java Date class: java.util.Date +Date() +Date(elapseTime: long) +toString(): String +getTime(): long +setTime(elapseTime: long): void Constructs a Date object for the current time. Constructs a Date object for a given time in milliseconds elapsed since January 1, 1970, GMT. Returns a string representing the date and time. Returns the number of milliseconds since January 1, 1970, GMT. Sets a new elapse time in the object. The + sign indicates public modifer...
Build a Date class and a main function to test it Specifications Below is the interface...
Build a Date class and a main function to test it Specifications Below is the interface for the Date class: it is our "contract" with you: you have to implement everything it describes, and show us that it works with a test harness that puts it through its paces. The comments in the interface below should be sufficient for you to understand the project (use these comments in your Date declaration), without the need of any further documentation. class Date...
C++ * Program 2:      Create a date class and Person Class.   Compose the date class...
C++ * Program 2:      Create a date class and Person Class.   Compose the date class in the person class.    First, Create a date class.    Which has integer month, day and year    Each with getters and setters. Be sure that you validate the getter function inputs:     2 digit months - validate 1-12 for month     2 digit day - 1-3? max for day - be sure the min-max number of days is validate for specific month...
Python: What are the defintions of the three method below for a class Date? class Date(object):...
Python: What are the defintions of the three method below for a class Date? class Date(object): "Represents a Calendar date"    def __init__(self, day=0, month=0, year=0): "Initialize" pass def __str__(self): "Return a printable string representing the date: m/d/y" pass    def before(self, other): "Is this date before that?"
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to...
public class AddValueNewArray { // You must define the addValueNew method, which behaves // similarly to the addValueTo method in AddValueToArray.java. // However, instead of adding the given value to the given // array, it will return a _new_ array, where the new array // is the result of adding the value to each element of the // given array. To be clear, the given array NEVER CHANGES. // // TODO - define your code below this comment // //...
Using the class Date that you defined in Exercise O3, write the definition of the class...
Using the class Date that you defined in Exercise O3, write the definition of the class named Employee with the following private instance variables: first name               -           class string last name                -           class string ID number             -           integer (the default ID number is 999999) birth day                -           class Date date hired               -           class Date base pay                 -           double precision (the default base pay is $0.00) The default constructor initializes the first name to “john”, the last name to “Doe”, and...
Java Program using Netbeans IDE Create class Date with the following capabilities: a. Output the date...
Java Program using Netbeans IDE Create class Date with the following capabilities: a. Output the date in multiple formats, such as MM/DD/YYYY June 14, 1992 DDD YYYY b. Use overloaded constructors to create Date objects initialized with dates of the formats in part (a). In the first case the constructor should receive three integer values. In the second case it should receive a String and two integer values. In the third case it should receive two integer values, the first...
Given the class Date that can prints the date in numerical form. Some applications might require...
Given the class Date that can prints the date in numerical form. Some applications might require the date to be printed in another form, such as October 1, 2020. Please do the following: Design the child class ExtDate based on the class Date (as a parent class) so that the date can be printed either form. Add a data member to the class ExtDate so that the month can also be stored in string form. Add a method to output...
// Programmer: // Date: // The Saurian class has the ability to translate English to Saurian...
// Programmer: // Date: // The Saurian class has the ability to translate English to Saurian // and Saurian to English public class Saurian {    // data    // constants used for translating    // note M = M and m = m so M and m are not needed    public static final char[] ENGLISHARR = {'A','B','C','D','E','F','G','H','I','J','K','L','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','n','o','p','q','r','s','t','u','v','w','x','y','z'};    public static final char[] SAURIANARR = {'U','R','S','T','O','V','W','X','A','Z','B','C','D','E','F','G','H','J','K','I','L','N','P','O','Q','u','r','s','t','o','v','w','x','a','z','b','c','d','e','f','g','h','j','k','i','l','n','p','o','q'};    public static final int ARRLENGTH = ENGLISHARR.length;   // should be the same...
The assignment is to write a class called data. A Date object is intented to represent...
The assignment is to write a class called data. A Date object is intented to represent a particuar date's month, day and year. It should be represented as an int. -- write a method called earlier_date. The method should return True or False, depending on whether or not one date is earlier than another. Keep in mind that a method is called using the "dot" syntax. Therefore, assuming that d1 and d2 are Date objects, a valid method called to...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT