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

后端 未结 2 1798
情话喂你
情话喂你 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.

提交回复
热议问题