Initialize a calendar in a constructor

65,298

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;
}
Share:
65,298
Favolas
Author by

Favolas

Updated on July 09, 2022

Comments

  • Favolas
    Favolas almost 2 years

    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 Calendar, and achieve the same as GregorianCalendar, when creating and initializing the object new Estimacao as above.

  • Mike Yockey
    Mike Yockey over 12 years
    Calendar isn't abstract, it just has no public Constructors.
  • Danny
    Danny over 12 years
    docs.oracle.com/javase/7/docs/api/java/util/Calendar.html check out the API, I think you will find it is abstract
  • Danny
    Danny over 12 years
    The Calendar class is an abstract class that provides methods for converting between a specific instant in time and a set of calendar fields such as YEAR, MONTH, DAY_OF_MONTH, HOUR, and so on, and for manipulating the calendar fields, such as getting the date of the next week.
  • Mike Yockey
    Mike Yockey over 12 years
    Indeed, in Java 7 it is. I'm looking at older Java docs. Looks to have been made abstract in Java 7.
  • Danny
    Danny over 12 years
    Check the API, Calendar is Abstract
  • Danny
    Danny over 12 years
    Nope, it has always been abstract
  • Danny
    Danny over 12 years
    pages.cs.wisc.edu/~cs368-1/JavaTutorial/jdk1.2/api/index.htm‌​l Here is Java 1.2 doc that shows it as Abstract
  • Mike Yockey
    Mike Yockey over 12 years
    Okay then, I stand corrected. It looks like we came up with the same solution though.