• Post Reply Bookmark Topic Watch Topic
  • New Topic

Has-A Relationship  RSS feed

 
Satendra Singh
Greenhorn
Posts: 9
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I create a class, Dog and Animal class has HAS-A relation on them.
I declared instance variable referring to Dog class in Animal class of two ways - one by new instance, and second one by just referring
Can anyone explain whats similarities and differences in those declaration and what impact on relationship






 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the first declaration you initialized the Dog while in the second you didn't initialize it. This doesn't change the relationship at all. It's still a has-A type relationship because in both cases an Animal has a Dog.
This is however probably not the correct type of relationship to use because it makes more sense to say that a Dog is an Animal than an Animal has a Dog.
 
Satendra Singh
Greenhorn
Posts: 9
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to know more about what would be impact on Dog class as we created object in Animal class--when we need initialization, when not. I mean, when we would create object either ways.

 
E Armitage
Rancher
Posts: 989
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You initialize when you create it if it must always exist. You can also initialize it from constructors within the Animal. There is no hard and fast rule that says whether you must or must not initialize it when you declare it. If you don't initialize it it will default to null. Whether that is what you want or not depends on your requirements. The bigger problem here could be that you are using the wrong type of relationship because a Dog is-A Animal.
 
Satendra Singh
Greenhorn
Posts: 9
Eclipse IDE Hibernate Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for your reply. Both initialization and not-initialization does same way as you said.

To correct myself the relation is like House has-a window.
 
Campbell Ritchie
Marshal
Posts: 56600
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, a house has‑a window.
I suggest, as a style thing, that you initialise the window/s in the constructor. That way
  • 1: Each house has a window
  • 2: The different houses can have different sizes of window
  • 3: You can avoid the window being null
  •  
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!