+ 1
Why do we need a constructor to set up start values for attributes when we can already set them right after declaring attributes
For example: public class Class{ int a = 3; int b = 5; Or: public class Class{ int a,b; public Class() { a = 3; b = 5; }
3 Réponses
+ 12
You can use different constructors for different objects. Constructors increase flexibility of the program. Also, inputs from the user can be given via an object to the constructor.
+ 11
Usually you pass the values for the attributes as arguments to the constructor and then set it there.
+ 3
Constructor is needed to initialize the initial state of the instance.
If you have one instance it is possible to initialize an attributes like in your first example, but if you have a hundreds of instances of one class you need a constructor.