Oracle Certified Professional Java Se 11 Developer · Free Practice Question Medium
Question 52
Question ID: UKOCP66115
Below are the possible definitions of Printable interface:
1.
public abstract interface Printable {}
2.
- public interface Printable {
- protected void print();
- }
3.
- public interface Printable {
- int i;
- void print();
- }
4.
- public interface Printable {
- void print();
- default void log() {
- }
- private default void log1() {
- }
- private static void log2() {
- }
- static int getNumLogs() {
- return -1;
- }
- }
5.
- @MarkerInterface
- public interface Printable {}
6.
- public interface Printable {
- public static final int x = 10;
- public final int y = 20;
- int z = 30;
- }
How many definitions are valid?
- A None of the definitions is valid
- B Only 1 definition is valid
- C 2 definitions are valid
- D 3 definitions are valid
- E 4 definitions are valid
- F 5 definitions are valid
-
G
All 6 definitions are valid
Reveal correct answer
Correct answer: C
Explanation
UKOCP66115:
public abstract interface Printable {}
✓ Valid, as interface in java is implicitly abstract, so using abstract keyword doesn't cause any error.
- public interface Printable {
- protected void print();
- }
✗ abstract method of the interface are implicitly public and if you provide access modifier for the abstract method of the interface, then only 'public' is allowed. As 'protected' is used for print() method, hence it causes compilation error.
- public interface Printable {
- int i;
- void print();
- }
✗ Variables declared inside interface are implicitly public, static and final and therefore compiler complains about un-initialized final variable i.
- public interface Printable {
- void print();
- default void log() {
- }
- private default void log1() {
- }
- private static void log2() {
- }
- static int getNumLogs() {
- return -1;
- }
- }
✗ As per Java 8, default and static methods were added in the interface and as per Java 9, private methods were added in the interface.
default modifier is not allowed with private method of the interface, hence method log1() causes compilation error. Methods print(), log(), log2() and getNumLogs() compile successfully.
- @MarkerInterface
- public interface Printable {}
✗ @MarkerInterface annotation is not available in Java and hence it causes compilation error.
- public interface Printable {
- public static final int x = 10;
- public final int y = 20;
- int z = 30;
- }
✓ Interfaces can define public, static and final variables and these modifiers are implicit.
Hence, for 'y' compiler adds static modifier and for 'z' compiler adds public, static and final modifiers.
Therefore, only 2 interface definitions are valid.
Discussion
Think the marked answer is wrong, or have a better explanation? Share it below — comments appear after review.
