I'm working on the Java OCP exam, and I came across this question
Given the following code:
Transaction t1 = new Transaction<>(1, 2); //1
Transaction t2 = new Transaction<>(1, "2"); //2
It is required that //1 must compile and //2 must NOT compile. Which of the following declarations of class Transaction will satisfy the request?
The answer is this one:
public class Transaction<T, S extends T> {
public Transaction(T t, S s) {
}
}
Which I understand. But when I put this code into an Eclipse project, it works! Here is my code:
class TransactionD<T, S extends T> {
public TransactionD(T t, S s){
System.out.println("D: t: " + t.getClass() + " s: " + s.getClass());
}
}
public class Test1
{
public static void main(String[] args) {
TransactionD d1 = new TransactionD<>(1, 2); //1
TransactionD d2 = new TransactionD<>(1, "2"); //2
}
}
My output is this:
D: t: class java.lang.Integer s: class java.lang.Integer
D: t: class java.lang.Integer s: class java.lang.String
My question is this: what am I missing?
Since you are using raw types in your declaration, you are actually using
TransactionD<Object, Object>
, and this makes the call valid, as according to java generics,Object
extendsObject
, and bothInteger
andString
also extend Object.