OCP Question 12, Explanation


interface Laughable {Joke crackJoke(String joke); }
class Joke {
    private String joke;
    public Joke(String joke) {
        this.joke = joke;

Which code fragment creates an instance of Joke?

A. Joke hello = Joke("MyJoke")::new;
B. Joke hello = Joke::new;
   Joke oneMore = hello::crackJoke("MyJoke");
C. Laughable joker = Joke::new;
   Joke oneMore = joker.crackJoke("MyJoke");
D. Joke oneMore = Laughable::new::crackJoke("MyJoke");

The correct answer is C.

We can strike options A, B and D out right away simply because there can be no args in metrefs (just in case: ‛metref’ stands for ‛method reference’).

There’s also plenty of other reasons why those options are syntactically invalid. For example, the first LOC in B thinks that Joke is a functional interface. Or take D: metrefs cannot be chained…

Well, the subject is so big we need a separate discussion. Note to self: write it.

On a side note I’d like to call your attention to something not related to metrefs per se but hugely important nonetheless. It’s about a class member or constructor being public in a non-public class (just look at that poor public Joke(String joke), for example). If there’s one good definition of sloppiness in coding, this is it. Speaks volumes… And is wide-spread. People just aren’t paying attention to what they are doing, even Java instructors and college profs (the following screenshot comes from https://www.youtube.com/watch?v=1SqE6If75TQ&t=390; jump to ~6:30 if playback starts at 0:00):

Yes, I did place that slide into my OCA-related e-learning course but haven’t provided explanation in the hope that users would figure it out on their own. Now it’s time to finally answer what’s so special about it: declaring a class member (or a ctor) public in a non-public class is totally meaningless because such class cannot be accessed from outside its package in the first place. On the other hand, a class member/ctor doesn’t have to be public to be available to any other class that belongs to the same package… As for the protected modifier, it’s entirely different story; such modifier can indeed be useful even when we stay within the same package.

Leave Comment

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