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.
Java Generic methods and generic classes enable programmers to specify, with a single method declaration, a set of related methods, or with a single class declaration, a set of related types, respectively. Generics also provide compile-time type safety that allows programmers to catch invalid types at compile time.
Generics enable the use of stronger type-checking, the elimination of casts, and the ability to develop generic algorithms. Without generics, many of the features that we use in Java today would not be possible.
Which of these is an correct way of defining generic method? Explanation: The syntax for a generic method includes a type parameter, inside angle brackets, and appears before the method's return type. For static generic methods, the type parameter section must appear before the method's return type. 5.
This does not work, because the class/method is generic and the caller of your class/method can set D
to MyAmericanEagle
.
Activate<MyAmericanEagle> active = new Activate<>();
Then your code would result in
MyAmericanEagle d = new MyWaterFowl();
Since that makes no sense (would result in ClassCastException) the compiler rejects it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With