1Z0-809: Java SE 8 Programmer II

Java SE 8 Programmer II

Question

Given: public class Test<T> { private T t; public T get (){ return t; } public void set (T t) { this.t = t; } public static void main (String args [ ] ) { Test<String> type = new Test<>(); Test type 1 = new Test ();//line n1 type.set("Java"); type1.set(100); //line n2 System.out.print(type.get() + " " + type1.get()); } } What is the result?

Answers

Explanations

Click on the arrows to vote for the correct answer

A. B. C. D.

A.

The given code defines a generic class Test with a type parameter T. The class has a private instance variable t of type T, a getter method get() that returns the value of t, and a setter method set() that sets the value of t. The main method creates two instances of the Test class: one with the type parameter String, and another one without a type parameter.

typescript
Test<String> type = new Test<>(); Test type1 = new Test();

The first instance type is created with the type parameter String, and therefore its get() and set() methods can only be used with values of type String. The second instance type1 is created without a type parameter, and therefore its get() and set() methods can be used with values of any type.

python
type.set("Java"); type1.set(100);

The set() method of type is called with a String value "Java", which is valid. The set() method of type1 is called with an int value 100, which is also valid because type1 does not have a type parameter and can accept any type of value.

csharp
System.out.print(type.get() + " " + type1.get());

The get() method of type is called and returns the String value "Java". The get() method of type1 is also called and returns the int value 100. The two values are concatenated with a space and printed to the console.

Therefore, the output of the program is:

Java 100

The correct answer is A.