javainheritancepolymorphism

java accidential implicit interface implementation


Recently came across an interesting feature, which, though, can result in a unexpected output of Eclipse "add unimplemented methods" feature. What is the "googl-able" name of the language concept behind this "occasional implicit implementation"?

I wouldn't expect the code below to compile but it did and is working

interface CallmeIfc {
  public void callme();
}

class CallmeCode {
  public void callme() {
    // implementation  
  }
}

class CallmeImpl extends CallmeCode implements CallmeIfc {
  // empty class body
}

public static void main(String[] args) {
  CallmeIfc me = (CallmeIfc) new CallmeImpl();
  me.callme(); // calls CallmeCode.callme()
}

Solution

  • Actually this looks like a compiler bug to me: The Java Language Specification writes:

    An instance method m1 declared in a class C overrides another instance method, m2, declared in class A iff all of the following are true:

    • C is a subclass of A.
    • The signature of m1 is a subsignature (§8.4.2) of the signature of m2.
    • Either
      • m2 is public, protected or declared with default access in the same package as C, or
      • m1 overrides a method m3, m3 distinct from m1, m3 distinct from m2, such that m3 overrides m2.

    In your case, the first condition is not satisfied: The method callme is declared in class CallMeCode, which is not a subtype of CallmeIfc.

    Edit: Bobah is right, the Spec distinguishes between implementing and overriding. In fact, it actually mandates the observed behaviour:

    Unless the class being declared is abstract, the declarations of all the method members of each direct superinterface must be implemented either by a declaration in this class or by an existing method declaration inherited from the direct superclass, because a class that is not abstract is not permitted to have abstract methods

    The Spec does not explain why.