Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Method Using Parameter That is a Subclass

 
Patrick Garner
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Does FloatDatum.greaterThanOrEqual() override Datum.greaterThanOrEqual()? I am trying to enforce the rule that a FloatDatum object can only compare itself to another FloatDatum object. In other words I am trying to disallow comparing a FloatDatum to another object that subclasses Datum. I am hoping that by overriding greaterThanOrEqual() the superclasses' version of greaterThanOrEqual() cannot be called by a FloatDatum object and hence, a FloatDatum object will not be allowed to compare itself to any other object that subclasses Datum. I want to prevent the following from happening:
FloatDatum fd = new FloatDatum(new Float(3.0));
IntDatum id = new IntDatum(new Integer(2));
if(fd.lessThan(id)) {
....
}
Books and online info that I've read says that, to override a method you must supply the same parameter type in the method signature. Can you override by supplying a parameter that subclasses the parameter in the method that you want to override? After all, a FloatDatum object is a Datum.
(edited by Cindy to format code)

[This message has been edited by Cindy Glass (edited July 24, 2001).]
 
Dave Vick
Ranch Hand
Posts: 3244
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Patrick
This is a fairly quick off the cuff answer I didn't test any of it but I think its correct...
You didn't override the super classes method you overrode it. Because you changed the arguments it can take it is an overload not an override.
I think that what will happen is that if you call your method with a subclass it will still use the superclasses method. The method call will look for a method that can take a subclass as an arguement and use it.
For instance if you have IntDatum and FloatDatum that both extend Datum and both overload the greaterThanOrEqual method then both will also get a copy of Datum's greaterThanOrEqual method. So calling the greaterThanOrEqual in one of the subclasses with any subclass of Datum as an arguement will end calling the super class method. Unless you use an arguement of the class that used as an arguement to overlaod the superclass method.
What you'll need to do is override the method by keeping the arguements the same and then putting in some osrt of check in the code to make sure both the calling instance and the arguement supplied are of the same class and not just related by a common ancestor.
hope that helps
Dave
If I'm way off base someone please correct me.

[This message has been edited by Dave Vick (edited July 24, 2001).]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic