tags:

views:

79

answers:

4

I wanted to add more methods to the Calendar from java.util.Calendar, but I'm having trouble using the getInstance method.

If I have an object like:
public class DateObject extends Calendar{ // other methods here }

And I do DateObject mon = DateObject.getInstance(); The code does not work. Even if I replace it with Calendar.getInstance(), I can't convert a Calendar to my DateObject.

How do I make my DateObject use getInstance()?

+1  A: 

getInstance() is a static/class method. You can't. What's your use case?

arcticpenguin
+8  A: 

getInstance() is a static method on Calendar. You cannot override static methods. You will need to provide your own method.

But I would question the design of extending Calendar. You will almost certainly be better served by having your class wrap a Calendar rather than extend it. In particular, changing your calendar implementation will become very, very difficult.

Consider also, that the Calendar API is very broken in a number of respects, so perpetuating it would be a crime against baby kittens.

Have you considered an alternative date/time/calendar library which might already contain the functionality you want? For example JodaTime.

dty
+2  A: 

Or, better yet, finding a library like Joda that will do whatever additional operations you seem to think are necessary. A design that extends Calendar is almost certainly headed in a bad direction.

duffymo
A: 

Creating a subclass of Calendar doe not mean that the existing static getInstance() method in Calendar will magically know

One solution is to add a method or methods with a signature like:

public static DateObject getInstance(...);

to the DateObject class, and implement it to create DateObject instances as required.

Another possibility is to look at how the existing getInstance() factory method works, and figure out how to get it to create one of your DateObject instances.

Also, pay attention to the answers that suggest that extending Calendar is a bad idea.

Stephen C