How do I make the method return type generic?

前端 未结 19 2646
無奈伤痛
無奈伤痛 2020-11-22 06:16

Consider this example (typical in OOP books):

I have an Animal class, where each Animal can have many friends.
And subclasses like

19条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 06:26

    As the question is based in hypothetical data here is a good exemple returning a generic that extends Comparable interface.

    public class MaximumTest {
        // find the max value using Comparable interface
        public static > T maximum(T x, T y, T z) {
            T max = x; // assume that x is initially the largest
    
            if (y.compareTo(max) > 0){
                max = y; // y is the large now
            }
            if (z.compareTo(max) > 0){
                max = z; // z is the large now
            }
            return max; // returns the maximum value
        }    
    
    
        //testing with an ordinary main method
        public static void main(String args[]) {
            System.out.printf("Maximum of %d, %d and %d is %d\n\n", 3, 4, 5, maximum(3, 4, 5));
            System.out.printf("Maximum of %.1f, %.1f and %.1f is %.1f\n\n", 6.6, 8.8, 7.7, maximum(6.6, 8.8, 7.7));
            System.out.printf("Maximum of %s, %s and %s is %s\n", "strawberry", "apple", "orange",
                    maximum("strawberry", "apple", "orange"));
        }
    }
    

提交回复
热议问题