Search code examples
javainterfaceabstract-class

Interface whose methods signature refer to an abstract class implementing that interface


I am not at all a JAVA expert but I've found that the following code snippets run.

interface Arithmetic {
    MyNumber somma(MyNumber b);
    MyNumber sottrai(MyNumber b);
    MyNumber moltiplica(MyNumber b);
    MyNumber dividi(MyNumber b);
}

abstract class MyNumber implements Arithmetic{
}

public class Test{
    public static void main(String[] args)
    {
        System.out.println("It works");
    }
}

Now in C++ you can do similar things if you do a forward declaration, in Java there's no such thing (to my knowledge) so I don't understand how can Arithmetic be compiled fine despite my MyNumber is actually declared after arithmetic. Is there a technicality of Java explaining this?


Solution

  • Java compilation occurs in multiple phases, one of these phases finds all of the declared class symbols and a later phase fills in all the classes' members (except for the already found nested class symbols).

    You can read about it here: https://github.com/openjdk/jdk/blob/master/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java