How to pass only some parameters to the constructor?
in
Programming Questions
•
6 months ago
I have a class with a lot of attributes. Each of those attributes have a default value.
Now I want to instantiate an object of this class by passing to the constructor only the parameters I want to be different from the default value.
How should I do this? I hope I don't have to write a constructor for every combination of parameters :-/
- class MyClass{
- int a1=1;
- int a2=2;
- int a3=3;
- ...
- MyClass(){
- //in this constructor no parameters are passed so every attribute keeps it's default value
- }
- }
Now I want to instantiate an object of this class by passing to the constructor only the parameters I want to be different from the default value.
- MyClass mc = new MyClass(a1=100, a5=500);
// I would like a constructor like this where I set the value to only some attributes of the class while others keep their default value
How should I do this? I hope I don't have to write a constructor for every combination of parameters :-/
2