How to return generic type from a method in java -
I'm new to generic here. Here are my classes.
public interface animal {zero} (); } The public class applies dogs to dogs (dismissed public) {System.out.println ("dog biscuit eats"); }} Public square cat follows the animal {dismissed public} {System.out.println ("Cat drink milk"); }} Now I want to use these sections in a normal way.
Public class GenericExample {public & lt; T Animal Extensions & gt; T method 1 () {// I want to return anything that extends the animal through this method using generics, how can I do it) public & lt; Expansion of t Animals & gt; T method 2 (T beast) {// I want to return anything that extends the animal using this method using genetics, how can I do this) Public static zero (string [] Args) {dog dogs = Method1 (); // a dog cat cat = method 2 (new cat ()); // Returns a Cat}} How can I return the normal type (can be a cat or dog) from methods "method1" and "method2" I have a number of methods that give "T Extension Animal", so it is better to declare the common type in any law level or class level.
You may not have a way to return to a normal type, and without the call without the method The caller is expected to reach that type of way, unless the logic of that kind can not be arbitrary. Therefore the examples of your main will not work. Then you are without generics, and either enter the return type manually
public animal method 1 (dog dog) = (dog) method 1 ( ) Or return subclass type to start with method.
Public dog method1 () Dog dog = method1 () Or you can go with generic, and either while calling method Specify the type
public & lt; T; T method 1 () Dog dog = & lt; Dogs & gt; Method 1 () Or pass the argument from which the type can be estimated (the second method is already satisfied):
Public & lt; T Animal Extensions & gt; In addition, you can only enter method1 From static main if this is stable .
Comments
Post a Comment