Question

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?

Was it helpful?

Solution

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) ?

OTHER TIPS

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.

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 :)

You should try to extend it:

class MyGregorianCalendar extends GregorianCalendar
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top