+ 2
Why should I use constructor, if I can use simple method to set an attribute value?
For example: public class Animal { private String sound; public void setSound (String newSound){ sound=newSound; } Animal Dog = new Animal(); dog.setSound("woow-woow"); System.out.println(dog.sound); } //output: woiw-woow // Constructor will work without this additional line dog.setSound("woow-woow"), so it makes the code shorter. Is it the only rteason, why using condtructor is better?
4 Respuestas
+ 4
Think of something like opening a Bank account. And account number must be set at the time of opening an account. And it cannot be changed thereafter. So, it totally depends on how your software should behave in reality.
+ 2
Generally most of us think that constructors are only used to initialize some variable but thats not the actual truth. In fact, constructors are those methods in a class which are fired upon the execution of the program. So, it depends on the user what he wants to accomplish.
For Example: I want to establiah a connection of my Program with some database right at the moment I execute a program and not when i "Click" on something, I will write that code in a constructor.
So now constructor will automatically fire that connection to the DB at the time you execute the program.
That hopefully explains what you were trying to ask here i.e Constructor will be fired right at the moment you execute the program but the method where you initialize the value might need a call via object of that class so its unnecessary and unprofessional way of doing something which can be done in a better way.
+ 1
1) Java allows objects to initialize themselves when they are created.
2) A Constructor initializes an object immediately
upon creation.
3) They have no return type and even void .
So many developers they use constructor for above purpose.
0
Thank you very much for your replies, everybody, I think I understand now!