javainheritancepackagecyclic

Understanding unusual behaviour with Java's cyclic inheritance


Consider the following two classes A and B (java) with various package considerations:

Both classes in the default package

public class A extends B {

  public static class C {}

}

-------------
public class B extends A.C {

  public B() {}

}

returns a cyclic inheritance error involving A

Class A in package called P1 and Class B in a package called P2

package P1;
import P2.B;

public class A extends B {

    public static class C {}

}

--------------
package P2;
import P1.A.C;

public class B extends C {

    public B() {}

}

Compiles without error. However, if I change the import statement in class B to import P1.A and then change the class definition to public class B extends A.C a cycle error shows again.

What explains this behaviour?


Solution

  • In the first example there is a cycle for A. If A extends B and B extends C, since C is an inner class in A the only way to reference it is to call A.C, so java recognises this a cycle on A:

    A-->B-->A.C (--> = extends).

    In the second example, the cycle is removed. By importing C through A, B no longer has to extend A.C, but rather simply C:

    A-->B-->C.

    So having B in a separate package allows the import of C directly instead of having to call it through A.

    In example 3 (where we import only P1.A), we would still have to refer to C as A.C, hence the reason the cycle returns.