If a class need multiple field information during object creation and also it is allowing fewer information.Than we have two option
1. Provide multiple constructor, or
2. Allow client to pass null argument while creating object.
Among these which is the best practice.
ex:
Case-1:
public class Test {
Test(A ob1,B ob2, C ob3){
}
Test(A ob1,B ob2){
this(ob1, ob2, null);
}
public static void main(String args[]){
Test ob = new Test(new A(),new B());
}
}
Case-2:
public class Test {
Test(A ob1,B ob2, C ob3){
}
public static void main(String args[]){
Test ob = new Test(new A(),new B(), null);
}
}
I have used main method in same class. Please consider these main methods in some other class.
You cannot pass the null value as a parameter to a Java scalar type method; Java scalar types are always non-nullable. However, Java object types can accept null values.
When we pass a null value to the method1 the compiler gets confused which method it has to select, as both are accepting the null. This compile time error wouldn't happen unless we intentionally pass null value.
It does not have a return type and its name is same as the class name. But, a constructor cannot be overridden. If you try to write a super class's constructor in the sub class compiler treats it as a method and expects a return type and generates a compile time error.
Overloaded constructors essentially have the same name (exact name of the class) and different by number and type of arguments. A constructor is called depending upon the number and type of arguments passed.
Using multiple constructors is the best. Many standard API libraries also have implemented it. Also It makes code loosely coupled and not a good practice to create the object by passing explicit 'null' value.
Case 2 increases chances of High coupling.
Apart from main question : Read More: Best way to handle multiple constructors in Java
EDIT:
Its better practice to use named factory methods to construct objects as they're more self-documenting than having multiple constructors. [Effective Java by Joshua Bloch]
Case 3, provide a method that will create the object.
public class A {
public static A create(B b) {
A a = new A();
a.setB(b);
}
public static A create(B b, C c) {
A a = create(b);
a.setC(c);
return a;
}
private A() {}
public void setB(B);
public void setC(C);
}
The constructor should be able to crate the object to prevent memory leaks. Less parameters in it minimize the situation when NullPointerException will occur. Providing a factory method like presented would decrease that risk and improve the control over object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With