0

Say I have the following interface:

public interface Renderer {
...
    public <T> void setBackingGraphics(T t);
}

How do I now implement the interface in a way that specifies what specific "T" to use?

@Override
public <Graphics> void setBackingGraphics(Graphics t) {
    ...
}

The above obviously doesn't work because "Graphics" will just be considered to be another placeholder. How do I actually make it "usable"? Let me demonstrate what I mean by using generic classes as example:

public interface A<T> {
    T someT();
}
public class C extends A<B> {
    B someT(){...}
}

How does the above work if I only want to apply it to specific methods?

  • 2
    Your method `public void setBackingGraphics(T t);` asserts that for any Renderer, for any value of `T`, you can call `setBackingGraphics(T)`. This is equivalent to having a non generic `setBackingGraphics(Object)`, but less clear, and no Renderer can be more specific without breaking the definition of Renderer. Just add it to the subinterface. – Jeff Bowman Dec 02 '17 at 03:33

1 Answers1

0

You need to be able to call the Renderer setBackingGraphics with any Object so the only thing you can do is:

@Override
public void setBackingGraphics(Object t) {
}

If you want something more specific you need to bound your parameter, for example:

public interface Renderer {
    public <T extends String> void setBackingGraphics(T t);
}

And then you can do:

@Override
public void setBackingGraphics(String t) {
}
Oleg
  • 6,124
  • 2
  • 23
  • 40
  • Ah, didn't know that. Too bad. Thank you for the answer though! (Small followup question: Would it be good practice to use something such as `...setBackingGraphics(Object o){if(!(o instanceof WhateverIWant)) throw new IllegalArgumentException() ...` in my subclasses? – Gandalf Smith Dec 02 '17 at 05:43
  • @GandalfSmith No, generally speaking using `instanceof` is not good practice. – Oleg Dec 02 '17 at 05:51
  • Hm, what should I do then to have a means of switching out the internals of my class without having to change any other class? – Gandalf Smith Dec 02 '17 at 17:45
  • @GandalfSmith Look into the visitor pattern https://stackoverflow.com/questions/255214/when-should-i-use-the-visitor-design-pattern – Oleg Dec 02 '17 at 18:31