abstract class & 'covariant' return type?
Hi Forum,
I have written an abstract class called 'Field', which within has an abstract method called 'getValue()'. So, so far I have:-
public abstract class Field
{
// instance variables
private double x;
private double y;
public Field(double x)
{
this.x = x;
}
public Field(double x, double y)
{
this.x = x;
this.y = y;
}
abstract double getValue();
}
Now, I have two subclasses of Field, called 'Real' and 'Complex', which both have concrete implementations of the method 'getValue()'. So, they both look like:-
public class Real extends Field
{
// instance variables
private double x;
public Real(double a)
{
super(a);
}
public double getValue()
{
return(this.x);
}
}
And, 'Complex' looks like:-
public class Complex extends Field
{
// instance variables
private double x;
private double y;
public Complex(double a, double b)
{
super(a, b);
}
public double getValue()
{
return(0.0);
}
}
Now, my problem is, is that I want the version of 'getValue()' in the Complex class to have a different return type than 'double'.Possibly for it to have either a 'void' or an error message.
I have tried messing around with generics, and also 'covariant return types', but cannot seem to get either to work without the compiler complaining. Any ideas appreciated.
Re: abstract class & 'covariant' return type?
If you want it to return something other than a double, than you don't want it to be a Field. Or if you want Fields to return something other than a double, you have to specify that. Simple as that.
You could throw an exception before the return statement though.
Or you could look into Double.NaN: Double (Java Platform SE 6)
Re: abstract class & 'covariant' return type?
Looks like if you want to return something other than a Double, you should re-evaluate your inheritance methods. Generics would work - but you don't post what you say didn't work so we can't help you with that unless you do (please use the code tags). Lastly, the wrapper class Double that Kevin referred to extends Number, so you could return a Number in which case the subclasses of Field could return Integer, Double, Byte, or anything else that extends Number.