Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cycles in interface hierarchies

Tags:

java

interface

With interfaces structure like this:

enter image description here

Why does not A-D-F yield an error since it is a cycle?

Note: An arrow A->B means A extends B

like image 791
user3520274 Avatar asked Apr 10 '14 16:04

user3520274


3 Answers

I tried to interpret your diagram in code as follows:

interface A extends B, C, D { }
interface B { }
interface C { }
interface D extends F{ }
interface E extends F{ }
interface F extends A{ }

And the compiler fails with the error:

java: cyclic inheritance involving A

So, as expected, cyclic inheritance is not allowed.

The error goes away if F does not extend A.

like image 95
Giovanni Botta Avatar answered Nov 11 '22 16:11

Giovanni Botta


It does yield an error, have you tried it?

interface A extends D {} // error on this line: The hierarchy of the type A is inconsistent
interface D extends F {} // error on this line: The hierarchy of the type D is inconsistent
interface F extends A {} // error on this line: Cycle detected: a cycle exists in the type hierarchy between F and A
like image 28
Mike B Avatar answered Nov 11 '22 17:11

Mike B


I have seen the following insane usage:

interface I {
    static final I CONSTANT = new C();
    ...
}

class C implements I {
}

The reason that this works, is that the .class (like a binary .obj) contains symbolic information on its imports. So a .java can be compiled to a .class. And then the linkage against other .class files may be done.

For the same reason (loose linkage) execution may fail, when compiled with a different version of a jar than at run-time.

Some compilers might balk at specific cycles though.


One addition though

If one interface uses constants from another interface, upon compilation those constants are stored in the .class file, and in effect the imports disappear. In that case there is at least one compiler, that does not detect dependencies, and a cycle may be broken. This might even lead to wrong, stale constants; an anti-pattern.

like image 32
Joop Eggen Avatar answered Nov 11 '22 17:11

Joop Eggen