Return to site

☕🎓JAVA CERTIFICATION QUESTION: interface implementation

· java

Given these four Java types:

package bot;
interface Command {
  String execute();
}

package bot;
public class Engine {
  public static void run(Command c) {
    System.out.println(c.execute());
  }
}

package bot;
import bot.command.AboutCommand;
public class Main {
  public static void main(String[] args) {
    AboutCommand ac = new AboutCommand();
    Engine.run(ac);
  }
}

package bot.command;
public class AboutCommand {
  String execute() {
    return "Chat Bot";
  }
}

What is the result? Choose one.

A. The code successfully compiles and prints Chat Bot.

B. The Command interface fails to compile.

C. The Engine class fails to compile.

D. The Main class fails to compile.

E. The AboutCommand class fails to compile.

#java #certificationquestion #ocp

Answer: the Main class does not compile.

Let's start with the Command interface, notice that the type declaration has no modifier.

This gives the interface package-level access, meaning it is accessible only within the bot package.

Next, the execute method is declared with no modifiers and has a semicolon instead of a body.

This is valid, and if a method is declared this way in an interface, it will be implicitly public and abstract.

From this, you can determine that the interface is accessible and valid.

Then, there is no reason for the Engine code to fail.

Also, AboutCommand does not contain the code that implements Command but compiles successfully.

Finally, look at the Main class.

It’s in the package bot, which has access to the Command type.

It imports the public type bot.command.AboutCommand, so it has access to that too.

The main method has a valid signature line, and that signature is consistent with a program entry point.

However, the body of the method has a problem.

The argument type for the Engine.run method must be assignment-compatible with Command.

However, as noted earlier, AboutCommand does not implement Command; therefore, it is not assignment-compatible with that type.

That means the code Engine.run(ac); will fail to compile.

Conclusion: the Main class does not compile.