Java – an instance that calls a static method
nice day!
I'm a little confused I want to use calendar, so I search it on the Internet and encounter the following code:
Ca1endar c = Calendar.getlnstance(); c.set(2011,2,5,1,25);
But I understand that this is a static approach:
Calendar.getlnstance();
If the method called is static, how can I get the calendar instance (abstract class)?
I really want to know about it So next time I can create a static method that can create instances
thank you.
Solution
This is a static factory method The idea is that a method is a method that calls the constructor, which returns the constructed object
return new SomeCalendar(Now);
Somecalendar is a concrete implementation of the abstract class calendar Some of the advantages are that you don't have to care about the underlying class (as long as you know it's just a calendar), and the underlying implementation can be changed without affecting you (for example, you can change the code to return to a new anothercalendar (), and you don't have to change anything in the code)
Because it is a static method, you can use it in the type itself (calendar. Getinstance();) Call it instead of an instance of this type (calendar c =...; c.getinstance();)