I want to know the exact scenario of using constructor over methods can anyone give me the exact example program for constructors over methods in java
-
3You question does not make much sense to me. Both are vital in some situations, and nonsense others. – Andrew Thompson Dec 25 '13 at 05:59
-
When to use field initialization via a constructor rather than setter methods? – Scary Wombat Dec 25 '13 at 06:00
-
A constructor creates objects. A method either requires an existing object or (for static methods) operates independently of an object. However, you're question doesn't really make sense. – Ted Hopp Dec 25 '13 at 06:05
-
A wild guess: Are you talking about factory methods? See http://stackoverflow.com/questions/9636243/do-we-ever-need-to-prefer-constructors-over-static-factory-methods-if-so-when – Jayan Dec 25 '13 at 06:08
-
When you want to construct an object and pass in values when doing so. – Dave Newton Dec 25 '13 at 06:08
-
Imagine you have a Calculator class with two fields, if both fields are necessary for the calculation, then it makes sense to ensure that they are set upon initialization of the Calculator object Calculator calc = new Calculator (2, 5); int result = calc.add (); On the other hand if you had Employee class where there were many non-mandatory fields e.g. `middleName`, then including this in the constructor would be annoying and better served by use of a setter method emp.setMiddleName ("Fred"); I hope this is what you were asking! – Scary Wombat Dec 25 '13 at 06:08
1 Answers
They are not similar things to compare even.
Both serves completely different purposes and even you have to note that constructor wont return anything, not even void :)
If you see a basic tutorial on Constructor, mentioned
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
So you cannot choose one over them.
If you are looking/talking about setting variables
of instance memebers, choose setter methods instead of variables.
Another scenoriao is some objects never complete without providing some basic info. In that cases you have to create a constructor
like it should be built when necessary info passed in constructor.
Consider the below scenorio, where to create an employee class, He must have an employee Id
public class Employee {
String empId;
public Employee(String empId) {
this.empId = empId;
}
// Methods
public static void main(String[] args) {
Employee a = new Employee("green");
}
Consider the below scenorio, where to create an empty employee class, later he can assign employee Id
public class Employee {
private String empId;
public Employee() {
}
// Methods
public void setEmpId(String empId) {
this.empId = empId;
}
public static void main(String[] args) {
Employee a = new Employee(); //No error
a.setEmpId("SOMEX007");
}
}

- 120,458
- 37
- 198
- 307