首页 > 解决方案 > Who is right and who is wrong? Oracle certification OCP. Inconsistency in the choice of answers

问题描述

What is printed by the following program?
`

public class Deer {
   enum Food {APPLES, BERRIES, GRASS}
   protected class Diet {
      private Food getFavorite() {
         return Food.BERRIES;
      }
   }
   public static void main(String[] seasons) {
      switch(new Diet().getFavorite()) {
         case APPLES: System.out.print("a");
         case BERRIES: System.out.print("b");
         default: System.out.print("c");
      }
   }
}

` enter image description here

The answer image is from OCP Test bank, in which I prepare my Oracle certification exam

My problem is I can't agree with the answer, that the Oracle company considers correct

I think most correct and accurate option is D.

My argument: main method is not guilty for improper declaration of Diet class. Error is occur when we type this class in switch statement incorrectly, in moment of declaration of class

Even full answer in the image explained that

I created this question because every score on a paid exam is at stake

I thought professional commerce company treats the drafting of questions carefully

How an exam participant can deal in this situation?

I please you tell me is it common have such ambiguous answers in IT certification exams?

Thanks in advance!

标签: javaoracleenumsswitch-statementmain

解决方案


答案 E 是正确的。无论您认为答案应该是什么,当我使用javac(Java 8 和 Java 16)编译代码时,唯一的编译错误是在main方法中。

$ javac Deer.java 
Deer.java:9: error: non-static variable this cannot be referenced
                    from a static context
      switch(new Diet().getFavorite()) {
             ^
1 error
$

编译错误消息有点奇怪......但它显然在main方法中。你可以自己重复这个实验。


你说你认为声明Diet是不恰当的,但我看不出有什么不妥之处。它看起来像一个普通的内部类声明。

代码中的问题不在于 的声明Diet,而在于main方法尝试创建Diet实例的方式。(语法上)正确的方法是写这样的东西(in main):

switch(new Deer().new Diet().getFavorite()) {

这说:

  • 创建外部类的实例Deer
  • Diet在实例中创建一个Deer实例
  • 调用实例getFavorite()上的方法。Diet

所以......显然......main做错了,这就是错误所在。编译器同意。

Java 语言规范 ( JLS 15.9.2 ) 证实了这一点:

如果 C 是内部成员类,则:

  • 如果类实例创建表达式不合格,则:

    • 如果类实例创建表达式出现在静态上下文中,则会发生编译时错误。

(你不会在 JLS 中找到任何东西来支持你的断言Diet是错误的......因为它没有错。但如果你愿意,请随时研究这个。)


元建议:在对 IT 认证考试的(假设的)问题和管理它们的公司进行咆哮之前......建议确保您掌握了正确的事实。

Java 语言有各种晦涩难懂的角落,即使在使用它 20 多年后,我仍然会不断发现我没有意识到(或已经忘记)的语言。假设你是对的是一个坏主意……面对可能的相反证据。


推荐阅读