简体   繁体   中英

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 AC a cycle error shows again.

What explains this behaviour?

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 AC , so java recognises this a cycle on A :

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

In the second example, the cycle is removed . By importing C through A , B no longer has to extend AC , 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 AC , hence the reason the cycle returns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM