Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I make the method return type generic?
    text
    copied!<p>Consider this example (typical in OOP books): </p> <p>I have an <code>Animal</code> class, where each <code>Animal</code> can have many friends.<br> And subclasses like <code>Dog</code>, <code>Duck</code>, <code>Mouse</code> etc which add specific behavior like <code>bark()</code>, <code>quack()</code> etc.</p> <p>Here's the <code>Animal</code> class:</p> <pre><code>public class Animal { private Map&lt;String,Animal&gt; friends = new HashMap&lt;&gt;(); public void addFriend(String name, Animal animal){ friends.put(name,animal); } public Animal callFriend(String name){ return friends.get(name); } } </code></pre> <p>And here's some code snippet with lots of typecasting:</p> <pre><code>Mouse jerry = new Mouse(); jerry.addFriend("spike", new Dog()); jerry.addFriend("quacker", new Duck()); ((Dog) jerry.callFriend("spike")).bark(); ((Duck) jerry.callFriend("quacker")).quack(); </code></pre> <p>Is there any way I can use generics for the return type to get rid of the typecasting, so that I can say </p> <pre><code>jerry.callFriend("spike").bark(); jerry.callFriend("quacker").quack(); </code></pre> <p>Here's some initial code with return type conveyed to the method as a parameter that's never used. </p> <pre><code>public&lt;T extends Animal&gt; T callFriend(String name, T unusedTypeObj){ return (T)friends.get(name); } </code></pre> <p>Is there a way to figure out the return type at runtime without the extra parameter using <code>instanceof</code>? Or at least by passing a class of the type instead of a dummy instance.<br> I understand generics are for compile time type-checking, but is there a workaround for this?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload