Favolas Favolas - 6 months ago 85
Java Question

Java Initialize an calendar in a constructor

If I do this:

new Estimacao("Aarão","Affenpinscher","Abóbora",new GregorianCalendar(1999,7,26),0),

Everything works as as expected.
But if i do this:

new Estimacao("Aarão","Affenpinscher","Abóbora",new Calendar(1999,7,26),0),

It can be done. As far as I know. We have to initialize calendar like this:

Calendar date = Calendar.getInstance();
date.set(Calendar.YEAR, 1999);
date.set(Calendar.MONTH, 7);
date.set(Calendar.DAY_OF_MONTH, 26);

The thing I want to know is if it's possible to use
, and achieve the same as
, when creating and initializing the object
new Estimacao
as above.




Calendar is an Abstract class, so you can't create an instance of it. When you call getInstance it actually returns a new GregorianCalendar instance. So it is the same as your first example.

So I guess the question is, why do you want to call new Calendar instead of new GregorianCalendar? If it is just so that you can hide the implementation you are using then I would either just do what you have already done to initialise a Calendar. Or create a single method that takes the same parameters and hides the calls to the Calendar class, e.g.

public Calendar getCalendar(int day, int month, int year) {
    Calendar date = Calendar.getInstance();
    date.set(Calendar.YEAR, year);

    // We will have to increment the month field by 1

    date.set(Calendar.MONTH, month+1);

    // As the month indexing starts with 0

    date.set(Calendar.DAY_OF_MONTH, day);

    return date;