java - 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");
}
}
}
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!
解决方案
答案 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 多年后,我仍然会不断发现我没有意识到(或已经忘记)的语言。假设你是对的是一个坏主意……面对可能的相反证据。
推荐阅读
- python - 如何创建多个条件的排列(没有长 if 条件)
- c# - 在不禁用命令的情况下禁用按钮单击事件?
- reactjs - 为什么高阶组件的语法经常采用高阶函数形式?而不是额外的论点?
- delphi - 有没有人将 IBX (Interbase Express) TClientDataSet -> TDatasetProvider -> TIBQuery 转换为 FireDAC?
- java - ORA-00905: missing keyword in case statement
- visual-studio-code - 使用 Mac 在 VS 上创建新项目
- sql - 为什么 postgreSQL INSERT 语句中复合类型的语法不同,并且取决于数据类型是命名还是未命名的事实?
- batch-processing - 在批处理脚本中过滤字符串中的单词
- android - Android ConstraintLayout 移动微调器的位置
- angular - 如何检索分组在 forkJoin 中的多个可观察对象的报告进度?