Why do we create a calendar class (abstract) in Java

I am a beginner Java programmer and I read about the Calendar class. This is an abstract class and all of its methods are static, but it is used as follows:

Calendar cal = Calendar.getInstance(); 

Where do you use cal to call methods like:

 cal.setTimeinMillis(day1); 

I am confused by this. When you call methods against a class, why do we need a reference variable and how is it legal for static methods?

+4
source share
4 answers
 Calendar cal = Calendar.getInstance(); 

Does not call the constructor, it just calls the (static) method, which returns an instance of some subclass (from Calendar ).

+8
source

Take a look at the documentation ; most Calendar methods that do something interesting (other than getInstance () methods) are not static and require an instance (which is really a container of the time instant represented by the calendar).

+3
source

1) The calendar is not Calandar

2) Calendar.getInstance() will return some specific calendar implementation, possibly GregorianCalendar .

3) cal.setTimeinMillis (day1); - an object method, not a static one.

+2
source

setTimeInMillis () is not static. The reason you need to call the getInstance () method to return the instance is because there are several getInstance () methods, and you can call them for different time zones and / or different locales than the default. Which time zone or locale you choose affects how other methods work.

+1
source

Source: https://habr.com/ru/post/1490562/


All Articles