views:

129

answers:

4

I'd like to make a method called "isBetween" returning a boolean, seeing if a GregorianCalendar date falls between two others. Alternatively, I'd like to just define operators of < and > for the class. I'm pretty new to Java, so I'm not sure....can I even do either of those? If so, how?

+1  A: 

No, you can't add method to pre-existing classes and you can't do operator overloading either in Java.

As an alternative, you could provide a static utility method in your own class for example.

Joachim Sauer
A: 

You should try to extend it:

class MyGregorianCalendar extends GregorianCalendar
Aito
+6  A: 

Java does not support monkeypatching or operator overloading, but feel free to subclass GregorianCalendar and add whatever methods you need.

But then, do you really need a new method to do cal.after(startCal) && cal.before(endCal) ?

Michael Borgwardt
Clearly, I missed the existence of before and after. I saw them about a minute before seeing your answer. Thanks
timdiggerm
@timdiggerm: the Calendar API is big and disorganized, so it's easy to overlook things, especially methods in the abstract superclass...
Michael Borgwardt
+1  A: 

I would advise against extending the class - you're not adding any behaviour which is specific to instances of a particular class, you're expressing logic which is applicable for any GregorianCalendar (or possibly any calendar at all).

As Joachim says, a static method in a utility class is the way to go - and if Java ever gains extension methods as per C# (I know they were suggested for Java 7, but I think they're out at the moment) you can modify them at that point.

Oh, and use Joda Time anyway :)

Jon Skeet