Java generics seem to work differently for classes than for methods
duck-typing, generics, java
Solution
It actually can be done.
The generic code between <>'s is fine. It's not different for methods and classes. Just needed to finish doing the dependency injection:
public class Activate<D extends CanQuack & CanWalk> {
private D d;
Activate(D d) {
this.d = d;
}
void doDuckLikeThings() {
d.quack();
d.walk();
//d.swim(); //Doesn't work
//And shouldn't since that was the whole point of ISP.
}
}
public class MainClass {
public static void main(String[] args) {
Activate<MyWaterFowl> a = new Activate<>(new MyWaterFowl());
a.doDuckLikeThings();
}
}
Thought I'd provide an answer that says what to do to fix it.
Problem
I'm following this: http://rickyclarkson.blogspot.com/2006/07/duck-typing-in-java-and-no-reflection.html And I'm trying to adapt this: ``` <T extends CanQuack & CanWalk> void doDucklikeThings(T t) { t.quack(); t.walk(); } ``` To this: ``` public class Activate<D extends CanQuack & CanWalk> { D d = new MyWaterFowl(); //Type mismatch } ``` Even though MyWaterFowl implements those interfaces. I'd like a solution that never mentions MyWaterFowl in the <>'s since I'm going to eventually just be injecting it (or anything else that implements those interfaces). If your answer is basically "You can't do that, what type would it even be?". Please explain why it's working for the method doDucklikeThings and conclusively state if it is impossible to do the same with a class or, if it is possible, how to do it. The T in doDucklikeThings must be something valid since it's working. If I passed that into a class what would I be passing in? As requested here's the MyWaterFowl code: ``` package singleResponsibilityPrinciple; interface CanWalk { public void walk(); } interface CanQuack { public void quack(); } interface CanSwim { public void swim(); } public class MyWaterFowl implements CanWalk, CanQuack, CanSwim { public void walk() { System.out.println("I'm walkin` here!"); } public void quack() { System.out.println("Quack!"); } public void swim() { System.out.println("Stroke! Stroke! Stroke!"); } } ``` Remember I've confirmed that doDucklikeThings works. I need the syntax that will let me inject anything that implements the required interfaces.