0

I have came across a scenario in my project where I have decided to use Builder pattern for creating objects of one of my Java class that extends some other Class (Super class is Third party api - can't modify their code) so how to initialize parent class object if child class is using Builder Pattern? Is it compulsory for parent class to use Builder pattern as well if child class is using it?

Loren
  • 320
  • 1
  • 10
  • 25
  • I think you can find your answer here: http://www.javabyexamples.com/lets-discuss-builder-pattern – Ali Choopani Jan 18 '21 at 14:18
  • @AliChoopani the way it is explained here it's too complicated :( – Loren Jan 18 '21 at 14:48
  • honestly I'm newby in java too and learned java builder pattern few weeks ago and this article helped me very much. i don't think there is any way to explain easier . – Ali Choopani Jan 18 '21 at 16:35
  • good news. i found this :) https://stackoverflow.com/questions/21086417/builder-pattern-and-inheritance – Ali Choopani Jan 18 '21 at 16:37
  • Does this answer your question? [Builder Pattern and Inheritance](https://stackoverflow.com/questions/21086417/builder-pattern-and-inheritance) – Melvin Jan 18 '21 at 17:27

1 Answers1

0

No, it is not compulsory. In the design and coding of your subclass, just do whatever is necessary to initialize the parent class. If you're using the builder pattern, that logic will likely go into your builder.

In many cases, it won't matter how the parent's initialization code was architected or what design patterns were used in its implementation. If the construction of the parent class involves a separate builder that is visible to you, it might make good sense for you to extend the idea of that builder and use the builder pattern to construct your own subclass. But doing that is in no way compulsory.

If you're talking about subclassing a third party class, then you have no control over how that superclass is constructed and initialized. You just do whatever you need to do to make use of the class, without worrying about how that class is coded. Think about it. Why would you care how the initialization of the superclass object is coded?

In short, do whatever you think makes the most sense given the definition of your problem and the tools you have at your disposal. Use the builder pattern or not based on if you think applying it improves your design and/or implementation.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44