-2

I have declared a Class Animal . And I have an interface Interface1. When I try to use a reference of this class in any method (let's take main method it gives a compile error)

public interface Interface1 {}

public class Animal<T extends Interface1> {}

public static <T>  void main(String[] args) {
   //Below line gives a compile error
   Animal<T> cc=null;   
} 

My question is:: in the main method type parameter T can also be a class or interface that extends Interface1 or is Interface1. So it should not give me a compile error.

Joby Wilson Mathews
  • 7,870
  • 2
  • 42
  • 43
Raj
  • 183
  • 1
  • 1
  • 8
  • For starters T is not within the specified bounds; you would need to ensure that it extends Interface1 before using to create an Animal Object reference. Besides, why have you bound a type parameter to the main method? – Zachary Jan 07 '18 at 01:59
  • 1
    `T` is not guaranteed to be a subtype of `Interface1`, and that's why compilation fails. Change to `public static void main(String[] args)`, except that: 1) The `main` method should not be templatized. 2) The generic parameter should somehow be related to the method signature, otherwise where would the actual `T` come from? – Andreas Jan 07 '18 at 01:59

1 Answers1

0

Suppose we want to restrict the type of objects that can be used in the parameterized type, for example in a method that compares two objects and we want to make sure that the accepted objects are Comparables. To declare a bounded type parameter, list the type parameter’s name, followed by the extends keyword, followed by its upper bound, similar like below method.

public static <T extends Comparable<T>> int compare(T t1, T t2)
   {
    return t1.compareTo(t2);
}

The invocation of these methods is similar to unbounded method except that if we will try to use any class that is not Comparable, it will throw compile time error.

Bounded type parameters can be used with methods as well as classes and interfaces.

Java Generics supports multiple bounds also, i.e . In this case A can be an interface or class. If A is class then B and C should be interfaces. We can’t have more than one class in multiple bounds.