Good day!
I am a little bit confused. I want to use a calendar so I searched it in the internet and encountered the following code:
Ca1endar c = Calendar.getlnstance();
c.set(2011,2, 5,1,25);
But I learned that this is a static method:
Calendar.getlnstance();
How come I can get the Instance of the Calendar(Abstract Class) if the method called is static?
I really want to understand it. So next time I can also create a Static method that can create an instance.
Thank you.
It's the static factory method. The idea is the method is the one calling the constructor and it returns the constructed object.
The body of Calendar.getInstance()
is perhaps something like this:
return new SomeCalendar(now);
where SomeCalender
is an concrete implementation of the abstract class Calendar
. Some of the advantages are: you don't have to care about the underlying class (as far as you know it's just a Calendar), and the underlying implementation can change without affecting you (for example, the code can be changed to return new AnotherCalendar()
and you don't have to change anything in your code)
Since it is a static method, you can call it on the type itself (Calendar.getInstance();
) as opposed to an instance of that type (Calendar c = ...; c.getInstance();
).
An instance method requires that you already have an instance to call the method on.
Being static does not mean that you can't take instances as a parameter, return an instance as a result or create an instance. It just means that the method can be called without first having an instance, and that in the method there is no such thing as this
.
You generally wouldn't want this sort of factory method to be an instance method (non-static) because it would mean you'd need to already have an instance to create a new one. How would you create the first one?
(Non-static factory methods do exist, but they are more commonly used for creating a different type of object. For example, a Builder or Factory class will typically have a method that creates instances of some other class.)
Java does this sort of thing all over the place. Look at the XML API.
This is a way to maintain a single interface into a Calendar
system even if the underlying implementation is changed. Yes the method is a factory method, however, the point some of the other answers seem to miss is that it can return different implementations of Calendar
.
That is how Calendar can be returned even if it is abstract. A overly simplified implementation of getInstance()
could be
Calendar getInstance()
{
return new GregorianCalendar();
}
The caller of getInstance()
does not need to know the implementation type in order to get the current date and time.
I recommend looking through OpenJDK
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With