Page 1 of 1

About Question enthuware.ocpjp.ii.v11.2.3455 :

Posted: Thu Jan 07, 2021 12:37 am
by teodorj
package foo;
import api.*;
import java.util.*;

public class DoNothingFilter implements Filter {

public DoNothingFilter(){
}

public static Filter provider(){
return new Filter(){
public List<String> filter(List<String> l) {
return l; }
};    }
}

It will not compile because it says it implements Filter but does not actually have the required filter method.
what if provider implementation both implement Filter and define public static provider method correctly?

Re: About Question enthuware.ocpjp.ii.v11.2.3455 :

Posted: Thu Jan 07, 2021 1:12 am
by admin
If a class says it implements a particular interface, then it must have the methods declared by that interface (or be abstract). If the DoNothingFilter class has "implements Filter" clause, then it must have public List<String> filter(List<String> l) method (or mark itself abstract).

>What if provider implementation both implement Filter and define public static provider method correctly?
Yes, that would be valid. Or you can just remove implements Filter clause from the class declaration.

As per https://docs.oracle.com/javase/9/docs/a ... oader.html, first the provider method is looked for. If the class has an appropriate provider method, then it doesn't matter whether it implements the interface.

Re: About Question enthuware.ocpjp.ii.v11.2.3455 :

Posted: Sun Apr 11, 2021 5:08 pm
by mohamed
Why answer number 2 is incorrect. It is said : If there is no provider method in the service provider class, then it must have a public no-args constructor.


Because I have created 2 modules to test : 1 service provider , 1 service interface and all works fine without the need to explicitly define a no-args constructor in the service provider module.

Re: About Question enthuware.ocpjp.ii.v11.2.3455 :

Posted: Sun Apr 11, 2021 10:38 pm
by admin
You have to use the service to cause an exception because that is when an instance of the service provider class will be created. If the service provider class does not have a provider method or does not any a no-args constructor, how will the underlying service loader framework create an instance?

Please go through this for details: https://docs.oracle.com/en/java/javase/ ... oader.html

Re: About Question enthuware.ocpjp.ii.v11.2.3455 :

Posted: Tue Apr 20, 2021 11:04 am
by mohamed
Ok I get it now. The answer 2 is not correct because there is already a constructor with 1 argument. So obviously the default no-arg constructor will not be automatically added.

The error is thrown at runtime : java.util.ServiceConfigurationError: XXX Unable to get public no-arg constructor.

Thank you