Other Implications – Generics

Other Implications

Enum Types

Because of the way enum types are implemented using the java.lang.Enum class, we cannot declare a generic enum type:

Click here to view code image

enum CoinToss<C> { HEAD, TAIL; }                  // Compile-time error!

An enum type can implement a parameterized interface, just like a non-generic class can. Example 11.21 shows the enum type TripleJump that implements the Comparator<TripleJump> interface.

Example 11.21 Enum Implements Parameterized Generic Interface

Click here to view code image

enum TripleJump implements java.util.Comparator<TripleJump> {
  HOP, STEP, JUMP;
  @Override public int compare(TripleJump a1, TripleJump a2) {
    return a1.compareTo(a2);
  }
}

Class Literals

Objects of the class Class<T> represent classes and interfaces at runtime. For example, an instance of the Class<String> represents the type String at runtime.

A class literal expression (using .class notation) can only use reifiable types as type parameters, as there is only one class object created for each reifiable type.

Click here to view code image

Class<Node> class0 = Node<Integer>.class;// Non-reifiable type. Compile-time error!
Class<Node> class1 = Node.class;        // Reifiable type. Ok.

The getClass() method of the Object class also returns a Class object. The actual result type of this object is Class<? extends |T|> where |T| is the erasure of the static type of the expression on which the getClass() method is called. The following code shows that all invocations of the generic type Node<T> are represented by a single class literal:

Click here to view code image

Node<Integer> intNode = new Node<>(2019, null);
Node<String> strNode = new Node<>(“Hi”, null);
Class<?> class2 = strNode.getClass();
Class<?> class3 = intNode.getClass();
assert class1 == class2;
assert class2 == class3;

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *