Initialize a calendar in a constructor
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;
}
Favolas
Updated on July 09, 2022Comments
-
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 asGregorianCalendar
, when creating and initializing the objectnew Estimacao
as above. -
Mike Yockey over 12 yearsCalendar isn't abstract, it just has no public Constructors.
-
Danny over 12 yearsdocs.oracle.com/javase/7/docs/api/java/util/Calendar.html check out the API, I think you will find it is abstract
-
Danny over 12 yearsThe 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 over 12 yearsIndeed, in Java 7 it is. I'm looking at older Java docs. Looks to have been made abstract in Java 7.
-
Danny over 12 yearsCheck the API, Calendar is Abstract
-
Danny over 12 yearsNope, it has always been abstract
-
Danny over 12 yearspages.cs.wisc.edu/~cs368-1/JavaTutorial/jdk1.2/api/index.html Here is Java 1.2 doc that shows it as Abstract
-
Mike Yockey over 12 yearsOkay then, I stand corrected. It looks like we came up with the same solution though.