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 - 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…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.
Contents
-
-
-
-
-
(Locked)
Generic class hierarchies8m 59s
-
(Locked)
Type argument hierarchies5m 36s
-
(Locked)
Understand type erasure in generics6m 26s
-
(Locked)
Understand bridge methods3m 12s
-
(Locked)
Understand type inference and target types17m 5s
-
Applying wildcard arguments21m 22s
-
(Locked)
Restrictions on generics4m 8s
-
(Locked)
-