Search code examples
javagenericsinterfacecompiler-construction

How does java compiler deal with code like `public interface A extends B<A>`


I just started writing java and today I read some code like this:

public interface A extends B<A>{
    ...
}

public interface B<E extends B<E>>{
    ...
}

Of course I can understand the code, but it makes me really confused. It looks like ... I used myself to create myself? How the compiler deal with it?


Solution

  • Yes it is astonishing what the compiler is capable of. As said by the other answer(s), generic parameters are used by reference. But there are compilations (.class) and their dependent relations. Notice: some runtime errors are caused by unsynchronized compilation, and you can store a .java file in a jar - I believe).

    That juggling with self-references is often used to pass the class of a child class to a super class for restricting things (methods) to the child class.

    But the same trick of cyclic behavior can be done as pure classes:

    public interface Foo {
        Foo ZERO = new Bar();
    }
    
    public class Bar implements Foo {
        ... ZERO ...
    }
    

    So the java compiler solves this chicken/egg problem.