Pass derived object into method wanting superclass ...
Hey All,
I have a little problem with inheritance ...
I have an interface
Code:
public interface Distance {
public double distance(Seq x, Seq y);
}
and a class DistributionalDistance which implements Distance:
Code:
public class DistributionalDistance implements Distance{
public double distance(QSeq x, QSeq y)
{
//calculates the distributional distance
}
}
The distance function in the Distance class needs objects of type Seq:
whereas that in the DistributionalDistance class takes objects of type QSeq:
Code:
public class QSeq extends Seq
Given than QSeq is a child class of Seq, is there a way to work things out here?
Eclipse suggested to either add unimplemented method,
Code:
@Override
public double distance(Seq x, Seq y) {
// TODO Auto-generated method stub
return 0;
}
(I'm not sure I even understand this piece of code.)
or to make DistributionalDistance abstract.
I don't understand why making it abstract would make the problem disappear.
Thanks for ur help,
-Azal.
Re: Pass derived object into method wanting superclass ...
If you want to implement an interface then you MUST implement the abstract methods of that interface. So your distance method in the DistributionalDistance class must have parameters of type Seq. Elsewhere in your code where you call the distance method and you pass it QSeq objects all will be fine if Qseq class extends Seq.
Re: Pass derived object into method wanting superclass ...
So here's what I did:
Code:
public double distance(Seq x, Seq y) throws IllegalArgumentException
{
if(x instanceof QSeq && y instanceof QSeq){
double d = //calculate distance using (QSeq)x and (QSeq)y
return d;
}
String e = "Arguments must be of type QSeq.";
throw new IllegalArgumentException(e);
}