Home > database >  Incompatible return Type while narrowing double to float
Incompatible return Type while narrowing double to float

Time:11-19

I'm writing my own implementation of an Vector. I want this to be as wide as possible so I wrote it with all fields and values being double. Now I made a second Object FloatVector which extends my main Class 2DVector. It's only job is to provide Getter-Methods of 2DVector that are already cast my double-Values to float-Values (I know, there are other - and probably better - ways of doing that, but I really can't be bothered adding (float) ... to everything related with my Vectors).

Anyway, while doing the above I ran into a problem I didn't expect to happen. Looking at the code below:

public class Vector2D {
    double x;
    
    public double getX() { return x;}
}
public class FloatVector extends 2DVector {
    @Override
    public float getX() {
        return (float) super.getX();
    }
}

Eclipse throws an Error, that The return Type is incompatible with Vector2D.getX() and I can't really understand why this is.

I tried replacing the primitive casting to the following:

@Override
public Float angleBetween() {
    return Float.valueOf( (float) super.getMagnitude() );
}

but also to no avail.

CodePudding user response:

The method in the subclass with the @Override annotation must have the same return type as the method in the superclass.

CodePudding user response:

try Generic Types

public class Vector2D<T> {
    T x;

    public T getX() {
        return x;
    }
}
public class FloatVector extends Vector2D<Float> {
    @Override
    public Float getX() {
        return super.getX();
    }
}
  • Related