Why is the super method not displayed / allowed?

interface Problematic {
    void method();
}
class Parent {
    void method(int arg) { }
}

class Child extends Parent {
    void test() {
        new Problematic() {
            @Override public void method() { 
                // javac error: method method in class <anonymous Problematic> cannot be applied to given types;
                // required: no arguments, found: int
                method(0);
                Child.this.method(0); // works just fine
                Child.super.method(0); // works just fine
            }
        };
    }
}

IntelliJ IDEA also gives a warning:

The 'method ()' method is infinitely recursive and can end only by throwing an exception

+4
source share
4 answers

From the Java language specification,

If the form MethodName, that is, only the identifier, then:

If the identifier appears in the visible declaration area of ​​a method with this name (§6.3, §6.4.1), then:

  • If there is a declaring declaration of a type in which this method is a member, let it Tbe the innermost declaration of that type. Class or interface to search for T.

  • " ". , . §6.5.7.1 .

  • - . , , (§15.12.2.1).

, Problematic. Child . T , . - T, .. Problematic.

, , Problematic#method() , . .

+4

. Problematic.method() Parent.method(int).

+1

, !

method(0) this.method(0), Child$1.this.method(0) Child$1.this.method(int) Problematic.

IDE.

, , , - - .

:

@Override public void method() { 
    // javac error: method method in class <anonymous Problematic> cannot be applied to given types;
    // required: no arguments, found: int
    method(0);
    Child.this.method(0); // works just fine
    Child.super.method(0); // works just fine
}

:

@Override public void method() { 
    // javac error: method method in class <anonymous Problematic> cannot be applied to given types;
    // required: no arguments, found: int
    this.method(0); // this is implied in the above code
                    // and resolves to the Problematic declaration
    Child.this.method(0); // will never be reached if the previous call is actually corrected.
    Child.super.method(0); // will never be reached either
}

this.method(0) , this.method(), StackOverflow.

IDE.

, , , , , this.XXX, .

If your goal is to call method(int)on Child, you already know how to do it, you must call it Child.this.method(int), it must be fully qualified due to the resolution of the scope of the namespace.

0
source

All Articles