0

I have the following interface:

public interface Box<T> {
    T get();
}

I'd like to be able to define another interface which is has Box<SomeType> as a parameter but for that interface to "know" what SomeType is.

e.g. I'd like to define the following interface

// this doesn't compile
public interface BiggerBox<B extends Box<H>> {
    H get();
}

The idea being you could do something like this:

BiggerBox<Box<String>> biggerBox = new SomeBiggerBox(new SomeBox("some string"));
String value = biggerBox.get();

The closest thing I can get to is:

public interface BiggerBox<B extends Box> {
    <U> U get();
}

But this has no compile-time type safety.

I think this is not possible in Java, but I would like to know if it is at all (even via mad hacks).

Edit: I don't want to add a second type parameter to the interface, i.e. no BiggerBox<Box<String>, String> (this is why I believe it's not possible)

2 Answers 2

2

You need to add that as a second type parameter:

public interface BiggerBox<B extends Box<H>, H> {
    H get();
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, but I only want to declare a single type, this will let me do BiggerBox<Box<H>, H> but I only want to declare BiggerBox<Box<H>>
1

There isn't anything in the BiggerBox methods that uses "B", so there's no reason to have it in the generic signature. There's also nothing in BiggerBox that forces "get" to come from the Box instance, nor anything to force a constructor to take a Box instance.

The implication is that BiggerBox should simply delegating "get" to a Box instance.

Here's an abstract class for this:

// Could also choose not to have it implement Box interface
public abstract class BiggerBox<T> implements Box<T> {

    private Box<T> box;

    public BiggerBox(Box<T> box) {
        this.box = box;
    }

    public T get() {
        return box.get();
    }
}

Or as an interface:

// Could also choose not to have it extend Box interface
public interface BiggerBox<T> extends Box<T> {

    Box<T> getBox();

    default T get() {
        return getBox().get();
    }
}

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.