0

Is it possible to have a constructor in a class, that you can ignore certain arguments/parameters?

For example, I have this constructor

Car(color, make, model, wheels, type, doors)

Could I call this constructor and not include the type parameter?

4
  • 3
    You can use optional parameters and overloads as with every other function. But only the last parameters can be optional, so only making type optional doesn't work. If both type and doors are optional, you could use named parameters to only specify doors but not type. Jun 17, 2014 at 15:15
  • 1
    As an alternative you could consider some kind of builder of factory. Jun 17, 2014 at 15:16
  • 1
    Optional parameters, as @CodesInChaos said,maybe ordering your parameters to have optional ones at the end. Otherwise you can add another constructor (overloading): Car(color, make, model, wheels, doors). In this case 'type' will have a default value (or a calculated one).
    – Fil
    Jun 17, 2014 at 15:21
  • Thank you, I believe this has helped me make some design decisions. Jun 17, 2014 at 15:22

1 Answer 1

3

Builder Pattern is exact solution to this problem. Especially if the combination of optional and required parameters get big, which would require tons of different constructors.

1
  • Thank you that link directly explains and will help me in the application I am building. The car was just an example and not the actual application I am building, but I will be able to transpose it for my problem set. Jun 17, 2014 at 16:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.