在Java中扩展日历 [英] Extending Calendar in Java
问题描述
我想从java.util.Calendar添加更多方法到日历,但是我在使用getInstance方法时遇到问题。
I wanted to add more methods to the Calendar from java.util.Calendar, but I'm having trouble using the getInstance method.
如果我有一个对象like:
public class DateObject extends Calendar {//这里的其他方法}
If I have an object like:
public class DateObject extends Calendar{ // other methods here }
我做 DateObject mon = DateObject.getInstance();
代码不工作。即使我用Calendar.getInstance()替换它,我不能将日历转换为我的DateObject。
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.
如何使我的DateObject使用getInstance()?
How do I make my DateObject use getInstance()?
推荐答案
getInstance()
是日历
。您不能覆盖静态方法。您需要提供自己的方法。
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.
还要考虑到,日历API在许多方面是非常破坏,因此永远是
Consider also, that the Calendar API is very broken in a number of respects, so perpetuating it would be a crime against baby kittens.
您是否考虑过可能已经包含所需功能的替代日期/时间/日历库?例如 JodaTime 。
Have you considered an alternative date/time/calendar library which might already contain the functionality you want? For example JodaTime.
这篇关于在Java中扩展日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!