I've a situation similar to this.
What if I still want to call constructors conditionally? (Though they said creating separate classes is suggestible)
Requirement structure:
Super class:
public class Super
{
public Super(DTO1 dto1Object){
this.dto1Object = dto1Object;
}
public Super(DTO2 dto2Object)){
this.dto2Object = dto2Object;
}
}
Derived class:
public class Derived extends Super
{
public Derived(Object obj)
{
//some_condition to check if passed object obj is dto1Object
//do something with dto1Object
//some_condition to check if passed object is dto2Object
//do something with dto2Object
}
}
How should I implement it?
EDIT:
Implemented it in this way based on the suggestion below:
Super class:
public class Super
{
protected static DTO1 dto1Obj;
protected static DTO2 dto2Obj;
public Super(DTO1 dto1Object){
this.dto1Object = dto1Object;
}
public Super(DTO2 dto2Object)){
this.dto2Object = dto2Object;
}
}
Derived class:
public class Derived extends Super
{
public Derived(DTO1 dto1Object){ super(dto1Object); }
public Derived(DTO2 dto2Object){ super(dto2Object); }
public static Derived create(Object obj) {
if (obj.equals(dto1Obj) {
return new Derived((DTO1) obj);
}
if (obj.equals(dto2Obj) {
return new Derived((DTO2) obj);
}
// ...
private String Function(String str){
if(create(dto1Obj).equals(dto1Obj) {
//do something
}
else if(create(dto2Obj).equals(dto2Obj)){
//do something else
}
return str;
}
}
}
EDIT2:
As per suggestion below, is this the correct way to use instanceof
?
if (create(dto1Obj) instanceof DTO1) {
//something
}
else if(create(dto2Obj) instanceof DTO2) {
//something else
}
Is shows the following error:
Incompatible conditional operand types Derived and DTO1
Incompatible conditional operand types Derived and DTO2