I’m working on an assignment has a class hierarchy like blow:
abstract EventClass
someEventClass1 extends EventClass
someEventClass2 extends EventClass
inside briefly:
abs EventClass{
//not in use just make it compile
int priority;
concrete compareTo(){
//need access priority when working in subclass}
}
someEventClass1 extends EventClass{
int priority;
}
in my EventClass I have a concrete method compareTo(Event in), which i expect it inherit by all subclasses
it will compare the priority(a int) of different events.
Obviously, inside this method I need to access priority within the subclasses. To make it compile I have to add a int priority in EventClass, and I was thinking I can shallow it in subclasses and it will works just fine with the compareTo inherited.
However, It’s not working properly, it seems the compareTo is not working.
If I erase the int priority and compareTo() in EventClass, put the compareTo into all my subclasses(ugly duplicated code). It works just fine…
Can some one help me to design this? Or tell me what I missed..
Thanks for any help!
Fields are not polymorphic in Java. Methods are. Add a
getPriority()method to theEventclass, and call this method from thecompareTomethod.You’ll then be able to override the getPriority method in the subclasses, and the appropriate method will be called, in a polymorphic way. Note that if the
getPrioritymethod is not used from the outside, you can make itprotected.Side note: please learn Java naming conventions and stick to them. And it would be easier to understand your question if you used real Java code rather than obscure pseudo-code.