1

I have two Interface here:

public interface Configuration {

}

public abstract interface Configurable {

    public Configurable setConfig(Configuration config);

}

And when one of my implementation tries to override the setConfig()method, the compiler will complain that is not overriding a super class method.

// This is not correct.
@Override
public SubConfigurable setConfig(SubConfiguration config) {
    this.config = config;
    return this;
}

I understand that I could always pass in a Configuration object and cast down to its real type but I am wondering if there is better way to target this. Or maybe I am just in a wrong design approach?

Thanks in advance.

1
  • I don't think that's the actual code. Did you mean SubConfiguration by chance? Commented Apr 3, 2014 at 0:12

2 Answers 2

4

It is possible to make the interface generic, specifying the type of configuration with a generic type parameter, with an upper bound.

public interface Configurable<C extends Configuration> {
    public Configurable setConfig(C config);
}

Then the subclass can specify which Configuration is required.

public class SubConfigurable implements Configurable<SubConfigurable> {

    @Override
    public SubConfigurable setConfig(SubConfiguration config) {
        this.config = config;
        return this;
    }
}

This is not necessary for the return type, because Java return types are covariant. A subclass can return a subtype of the original method and still override that original method. Parameter types in overriding methods are not covariant, but using generics in this way is a valid solution.

Sign up to request clarification or add additional context in comments.

2 Comments

And I think Configurable#setConfig should then be declared to return a Configurable<C> to work completely generically.
That is exactly what I was looking for! Thx. Actually I tried the other way around (Configuration<T extends Configurable>) and it did not work. I think I still need to understand generic more.
0

Take a look at Java Generics. Also java interface does not have to implicitly be declared as abstract, it is already abstract.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.