What are nested objects in OOP concept? (mainly in java)
What are nested objects in OOP concept? (mainly in java)
It was asked in an interview that what are nested objects ? give a real life example also.
I end up saying that if we create an object of class B in class A and when the object of class A will be created then Class A object will already be having Class B object and that's called nested object.
Nested objects are good for organize your class visiblity inside of main class. If you need class which is in context with main class and her purpose is only for her and you never need instanted this class outside of main class its good use this nested "hidden" classes in context of main class.
– daremachine
Aug 24 at 3:21
1 Answer
1
While you are absolutely right with your answer, here are few more details about it.
The thing you are talking about is actually Containment
or HAS-A
relationship. There are two types of containments in OOP.
Containment
HAS-A
Consider A
HAS-A
B
A
HAS-A
B
Composition:
It is a type of containment where B
cannot exist if A
dies. Best example is a House has-a
room. If house is destroyed, room has no existence.
B
A
has-a
Aggregation:
It is a type of containment where B
can still exist even if A
dies. Example for this is
Employee has-a
department. Even if employee is destroyed, the department will still exist
B
A
has-a
Containment is not composition (has-a). For composition you can define the other object anywhere. Nested objects are probably inner classes in Java. Also, as a counter example: If I have a car which has-a set of tires, the tires can exist after the car is gone. I can put them on another car, or make them a swing for the kids.
– Robert
Aug 24 at 4:03
Wikipedia: Containment. I don't see any reason why Composition is not Containment. There is a difference between Nested Classes and Nested Objects. OP has referred to Nested Objects and not classes. I don't think my answer deserves a downvote.
– Amit Phaltankar
Aug 24 at 4:24
I didn't downvote you... and you may be right...I may have misunderstood the question. Now I am unsure if the question is about composition or inner classes.
– Robert
Aug 24 at 14:11
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You are completely right!
– Michael Montero
Aug 24 at 3:11