From the course: Java: Generic Classes

Unlock this course with a free trial

Join today to access over 25,500 courses taught by industry experts.

Restrictions on generics

Restrictions on generics - Java Tutorial

From the course: Java: Generic Classes

Restrictions on generics

- [Narrator] We have looked at a couple of rules in generics in the first module, but there is an additional set of restrictions that you need to be aware of. The first one is with type parameters. The rule is that you cannot instantiate a type parameter. This means you cannot write code like this, Tt = new T(). Remember that T is just a placeholder and will be replaced by the desired type argument that you pass when you invoke your generic type. The next restriction is for static fields. You cannot declare static fields in your code whose types are type parameters. Static fields or methods are always defined for the class level. They are never associated with any particular instance of the class. So let's say, in your box class, you declare a static field like this, private static T t; and then you create two instances of the box class, Box<Fruit> and Box<Book>. In that case, it is not possible to determine which of…

Contents