Does a class which implements an interface's method (without explicitly implementing that interface) extend that specific interface?

3425 views java

I am implementing a class to store objects that can be assigned a double value. For this reason, I have created a HasDoubleValue interface, that contains a single method:

public interface HasDoubleValue{
    public double doubleValue();

My main class is defined as such:

Data <O extends HasDoubleValue> {...}

Now, when I try to initialize this class to store Integers, I get a "type argument Integer is not within bounds of type-variable O" error, although Integer implements the doubleValue() method by default.

I suppose that this happens because Integer does not explicitly implement my HasDoubleValue interface, although it has the method I am looking for. Is this right? What would a natural workaround be?

answered question

In the case, using a DoubleSupplier as a lambda would allow you call it without changing the classes involved.

1 Answer


Yes, it is right. Java doesn't use duck-typing as JavaScript or TypeScript.

A solution is to create an adapter class that wraps a Integer, delegates to it, and actually implement the interface.

Or, since inthis case your interface is a functional interface, to use a lambda or a method reference to create an instance of HasDoubleValue from an Integer.

posted this

Have an answer?


Please login first before posting an answer.