+ 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?

25th Jun 2016, 9:43 PM
Maxim Velichkin
Maxim Velichkin - avatar
4 Réponses
+ 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.
26th Jun 2016, 8:55 AM
Jigar Thacker
Jigar Thacker - avatar
+ 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.
26th Jun 2016, 2:14 AM
Avtar Sanju
Avtar Sanju - avatar
+ 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.
25th Jun 2016, 11:21 PM
Aamir Memon
Aamir Memon - avatar
0
Thank you very much for your replies, everybody, I think I understand now!
27th Jun 2016, 9:13 PM
Maxim Velichkin
Maxim Velichkin - avatar