Is it possible for two classes to be data members of each other mutually?

后端 未结 2 1799
情话喂你
情话喂你 2021-01-23 15:57

Is it possible for a class A to be a field of another class B and at the same time, for class B to be a field of Class A?

I have a scenario where I have two classes: Mat

相关标签:
2条回答
  • 2021-01-23 16:22

    Yes, Java actually supports cyclic dependencies between classes. So what you are asking is achievable but as the other answer pointed out it would cause some problems at construction time. I mean one constructor calling another might cause an overflow error. So instead you can do something like.

    Match match = new Match();
    Venue venue = new Venue();
    match.setVenue(venue);
    venue.setMatch(match);
    

    In view of Garbage collection, If Match and Venue were to be referenced to each other and not by any other objects then they would be in a state of isolation ie Island of Isolation. They won't be eligible for garbage collection. I hope this helps.

    0 讨论(0)
  • 2021-01-23 16:32

    Yes it is possible, but I doubt it can be achieved during object construction time, which causes cyclic dependency.

    First create classA and classB objects and assign the mutual reference by using setter of each objects.

    0 讨论(0)
提交回复
热议问题