Hi all:
I am a reader of 'Thinking in
Java' and now had an OO design question...
The question is a little difficult....
(I am from Taiwan , I can only use easier English)
From 'Thinking in Java 2nd edition' page 360 , Month2.java
Bruce introduced a design trick , that uses Month2 for each Month's type.
I want to rewrite this code and implement 'Comparable' interface , as follows :
After this , I want to introduce a 'Season' interface as following:
This interface is very simple , just wrap a 'feeling' to each MyMonth
In Northern Hemisphere ,
For example : March,April,and May are 'warm' ,
so , getFeeling() should return 'warm'
and June,July,Auguse are 'hot' , so , getFeeling() return 'hot' ...etc
To accomplish this , I extend MyMonth and implements SeasonIF,
The new class is named "NorthMonth.java" (Northern Hemisphere)
The code is as follows :
OK, here is the problem , in fact , the code above is incorrect.
Because 'getIndex()' is from 'MyMonth' and it looks up the index from 'MyMonthList',
It will never find getIndex(NorthMonth) from 'MyMonthList',
therefore , the return value will always be '-1'.
But I don't know how to overcome this , let's skip this...
And if I write a client to
test my NorthMonth , the result will be :
The program runs with the error:
ClassCastException: test.MyMonth
I know the error's origin is '(NorthMonth)(MyMonth.APR)'
but I don't know how go fix it....
I've tried many ways to rewrite my client code (testNorthMonth.java)
and NorthMonth.java , but I find no way to solve the problem 'elegantly' ...
The only solution I found is very DIRTY :
I have to re-code almost all 'MyMonth.java' to 'NorthMonth.java'
including initializing twelve static NorthMonth (from JAN to DEC) ,
private static NorthMonth[] NorthMonthArray ,
private static List NorthMonthList = Arrays.asList(NorthMonthArray) ,
public int getIndex(NorthMonth nm) ,
public int compareTo()...
By this way , it really works , but it is too dirty ....
It lacks the 'elegance' , 'elasticity' and 'code-reusability' of Object-oriented Java
If there are some presuppositions:
1. Do not initialize 12 static NorthMonth in NorthMonth.java
2. Do not re-code getIndex() and compareTo() , which should be handled by MyMonth.java
3. Only implement getFeeling()
4. In MyMonth.java , each month is 'MyMonth' , not integer-based
5. MyMonth not abstract .
Do you have better idea how to improve the design ?
Thank you very much.
Best regards.
[ edited to preserve formatting using the [code] and [/code]
UBB tags -ds ]
[ August 11, 2002: Message edited by: Dirk Schreckmann ]