Java OCA OCP Practice Question 2127

Question

determine the behavior of this program:.

import java.io.*;

class LastError<T> {
     private T lastError;
     void setError(T t){
         lastError = t;//ww  w .ja v a  2 s. c  o m
         System.out.println("LastError: setError");
     }
}

class StrLastError<S extends CharSequence> extends LastError<String>{
     public StrLastError(S s) {
     }
     void setError(S s){
        System.out.println("StrLastError: setError");
     }
}

public class Test {
     public static void main(String []args) {
        StrLastError<String> err = new StrLastError<String>("Error");
        err.setError("Last error");
     }
}
a.   it prints the following: StrLastError: setError
B.   it prints the following: LastError: setError
C.   it results in a compilation error
d.   it results in a runtime exception


C.

Note

It looks like the setError() method in StrLastError is overriding setError() in the LastError class.

At the time of compilation, the knowledge of type S is not available.

Therefore, the compiler records the signatures of these two methods as setError(String) in superclass and setError(S_extends_CharSequence) in subclass?treating them as overloaded methods (not overridden).

In this case, when the call to setError() is found, the compiler finds both the overloaded methods matching, resulting in the ambiguous method call error.




PreviousNext

Related