Overriding a Method Using a Parameter That is a Subclass

abstract class Datum {

private Object value;

private Object name;

...

Datum(Object value) {

this.value = value;

}

Object getValue(){

return value;

}

abstract boolean lessThan(Datum d);

boolean greaterThanOrEqual(Datum d) {

return !lessThan(d);

}

}

class FloatDatum extends Datum {

FloatDatum(Float value) {

super(value);

}

boolean lessThan(FloatDatum fd){

return (((Float)getValue()).compareTo((Float)fd.getValue()) < 0);

}

boolean greaterThanOrEqual(FloatDatum fd) {

return super.greaterThanOrEqual((Float)fd.getValue());

}

}

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.

[1746 byte] By [pgarner] at [2007-9-26 1:49:06]
# 1

I don't think it will overrride is since it has a different input type. No idea what exactly will happen.

I think the following structure would serve your needs better:

abstract class Datum

......

boolean lessThen(Datum d) throws WrongSortOfDatumEXception;

(graterthenorequal defined similiar but also throwing

}

public class FloatDatum extends Datum

{

constructors

/** only accepts FloatDatum*/

boolean lessThen(Datum d)

{

if(check if d is not Floatdatum)

{

throw a Exception

}

your normal code for comparing floatdata

}

arcosh at 2007-6-29 2:53:36 > top of Java-index,Archived Forums,Java Programming...
# 2
No, what you describe is not an override. I speak from experience as I expected it would be, and spent several hours finding out why my program did not work as I thought it should.
DrClap at 2007-6-29 2:53:36 > top of Java-index,Archived Forums,Java Programming...
# 3
Declaring a method with different arguments is overloading, not overriding.
schapel at 2007-6-29 2:53:36 > top of Java-index,Archived Forums,Java Programming...