nerdexam
Oracle

1Z0-829 · Question #36

Given: interface IFace { public void m1(); public default void m2() { System.out.println("m2"); } public static void m3() { System.out.println("m3"); } private void m4() { System.out.println("m4")…

The correct answer is D. new MyC().m2 (). B and D are the two correct invocations (the answer key appears incomplete by listing only D). D works because m2() is a default method - it has a concrete body in the interface and is inherited by MyC, so calling it on a MyC instance is perfectly valid. B works because m3() is…

Utilizing Java Object-Oriented Approach

Question

Given: interface IFace { public void m1(); public default void m2() { System.out.println("m2"); } public static void m3() { System.out.println("m3"); } private void m4() { System.out.println("m4"); } } class MyC implements IFace { public void m1() { System.out.println("Hello"); } } Which two method invocation execute?

Options

  • AIFace myclassobj = new Myc (); myclassobj.m3();
  • BIFace.m3();
  • CIFace muclassobj = new Myc (); myclassobj.m4();
  • Dnew MyC().m2 ();
  • EIFace.m4();
  • FIFace.m2();

How the community answered

(44 responses)
  • A
    2% (1)
  • B
    11% (5)
  • D
    80% (35)
  • E
    2% (1)
  • F
    5% (2)

Explanation

B and D are the two correct invocations (the answer key appears incomplete by listing only D).

D works because m2() is a default method - it has a concrete body in the interface and is inherited by MyC, so calling it on a MyC instance is perfectly valid. B works because m3() is a static interface method, and static interface methods must be called directly on the interface name (IFace.m3()), which is exactly what B does.

A fails for the same reason as B succeeds in reverse: static interface methods cannot be invoked through a reference variable (even one typed as the interface) - the compiler enforces calling them only via IFace.m3(). C and E both fail because m4() is private to the interface - it's only accessible internally and cannot be called from any outside class or reference. F fails because m2() is a default (instance) method, not static, so IFace.m2() is a compile error - you need an instance to call it.

Memory tip: Think in three buckets - default methods need an instance, static methods need the interface name, and private methods stay inside the interface forever. If the call site doesn't match the bucket, it won't compile.

Topics

#interface methods#default methods#static methods#method visibility

Community Discussion

No community discussion yet for this question.

Full 1Z0-829 Practice