Valtteri Valtteri - 5 months ago 8
Java Question

Cyclic inheritance uses

So if I write the following code in Java:

public class A extends A{
public static void main(String[] args){

This gives a compiler error message cyclic inheritance involving A.

The same happens if I write two classes A and B and A inherits B and B inherits A.

This makes sense to me, as it is quite hard to imagine how this would be possible anyway.

I then asked about this from one of the professors at my uni. He said there are languages where this is possible and he lamented how this is not possible in Java and that he had done some projects where he had used cyclic inheritance and so on, but I couldn't really understand any of it. He also mentioned he had had problems where he would have liked to use cyclic inheritance.

Can you educate me on the possible uses of this strange phenomena of cyclic inheritance? When is it possible and how? Are there problems where this could be useful?


I dug up this interesting reference: basically it says that cyclic inheritance is valid as long as there are no repeated fields, as the lookup for any field just needs to traverse one loop of the cycle to find out a meaning. If a field is repeated then none of the two definitions is more valid than the other and apparently there would be a problem.

So suppose that you want to define a person as a human and as a voter, and set different attributes for each. In pseudo-code:

class Person extends Human:
  String name;

class Human extends Voter:
  String language;

class Voter extends Person:
  Country residence;

Now you can address different aspects of an individual without having to define a hierarchy, and you might instantiate different people as a Person (with name), a Human (that speaks a language) or a Voter (in a particular country). No aspect is more important than the other.

While interesting, I don't think it is practical to use outside of research projects. Imagine having constructors for all classes that pass parameters to the super() constructors -- it would be easy to mess up the whole construct.