Return to site

JAVA CERTIFICATION QUESTION: Enum and abstract member

· java

Given:

public class Main {
    public static void main(String[] args){
        Score minus = Score.MINUS;
        System.out.println(minus.getScore());
    }
}

enum Score {
    PLUS(), MINUS() {
        int i = 10;

        int getScore() {
            return i++;
        }
    };

    int i = 0;

    abstract int getScore();
}

What is the output?

  • A. Compilation fails in enum Score
  • B. Compilation fails in class Main
  • C. 0
  • D. 1
  • E. 10
  • F. 11

 

 

#java #certificationquestion #ocp

Enum DOWN constant is rewritten with an anonymous class. But not the PLUS constant.

It is a compile-time error according to JLS section 8.9.2:

"It is a compile-time error if an enum declaration E has an abstract method m as a member,

unless E has at least one enum constant and

all of E's enum constants have class bodies that provide concrete implementations of m."

So, in order to compile, UP must have a body like

UP {
  int getScore() {
   return 0;
   }
}

·Ɐ sᴉ ɹǝʍsuɐ ʇɔǝɹɹoɔ ǝɥʇ :uoᴉsnʅɔuoꓛ