CS2030 AY19/20 Semester 2
  • Introduction
  • Textbook Contributions
  • Peer Learning Tasks
  • Piazza Participation
  • Setting Up Lab Environment
  • Setting Up Java
  • Setting Up Vim
  • Setting Up MacVim
  • Setting Up Sunfire and PE Nodes
  • Setting Up Checkstyle
  • Textbook
  • CS2030 Java Style Guide
  • CS2030 Javadoc Specification
  • JDK 11 Download Link
  • Codecrunch
  • Github Repo
  • Piazza Forum

  • Declaration of Generics in Static Methods


    Edit the material here!

    This was adapted from Question 521 from Piazza.

    Given the following set of code:

    public class Box<T> {
    public static <T> Box<T> of () {};
    }

    We discover that we will need to declare <T> once again. Is there a particular reason why <T> needs to be added before Box<T> for static methods as shown above?

    Well as we remmeber, static methods belong to the class, while non-static methods belong to the instance of the class.

    Different instances of the class Box, may have different type parameters <T>, i.e. Box of different types, Box<Integer>, Box<String> etc. However, static methods, as well as static variables, are class level so all instances of the class Box have access to the same static of() method.

    That would not be possible if the type parameter of the static method is referring to the class type parameter <T>, since <T> may differ across instances of the class Box. Therefore, what we need to do is to define a local type parameter specific to the scope of the static method.

    The type parameter U created in static <U>, is then infered by Java for U in Box<U> ,U in argument (U u), and U in the return type of new Box<U>(), or just new Box<>() for short.

    In conclusion, as stated in the lecture note, the <T>in the static method has no relation with the class type <T> in Box <T>. To minimize confusion, a different letter may be used for your static method (eg. <U>), in contract to the type parameter(eg. <T>) in you main class.