Reputation: 31
I'm making a Date class for my school work which basically do some basic features just like API Date. Non of the methods are allowed to associate with the API Date class of Java except for one of the constructors which set to current local time. I'm having trouble setting it up with the error on the instance i made for it.
import java.util.*;
public class Date
{
// declare needed variables
private int day;
private int month;
private int year;
/**
* Default constructor to set the date info to the current date
*/
public Date()
{
// I have trouble assign Date using the Java API Date class
Date d1 = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(d1);
day= cal.get(Calendar.DAY_OF_MONTH);
month = cal.get(Calendar.MONTH);
year = cal.get(Calendar.YEAR);
}
/**
* Overloaded constructor to set the date info based on user input
* @param int inMonth to input month value
* @param int inDay to input day value
* @param int inYear to input year value
*
*/
public Date( int inMonth, int inDay, int inYear)
{
//set all the inputs into suitable variables
day = inDay;
month = inMonth;
year = inYear;
}
}
Error: incompatible type: Date cannot be converted to java.util.Date
Upvotes: 0
Views: 871
Reputation: 86324
/**
* Default constructor to set the date info to the current date
*/
public Date()
{
// The solution is to use LocalDate
LocalDate d1 = LocalDate.now(ZoneId.systemDefault());
// I am leaving the rest to yourself, it shouldn’t be hard
}
The java.util.Date
class that you were trying to use (I think) is poorly designed and long outdated. LocalDate
from java.time, the modern Java date and time API, is so much nicer to work with. LocalDate
has the methods you need for getting the year, month and day of month as integers.
And then you don’t need to rename your own class.
No, you can use a class that has the same name as the class you are declaring. Only you cannot import that other class. Instead you can refer to it by qualified name, that is, the class name prefixed by the package name:
java.util.Date d1 = new java.util.Date();
In this case you wouldn’t want to, but it’s nice to know. You may need it for some other class some other time.
LocalDate
Upvotes: 0
Reputation: 973
Rename your class and constructors to "MyDate" or any name other than Date.
Upvotes: 1