【发布时间】:2018-01-30 15:43:44
【问题描述】:
我的情况类似于this。
如果我仍然想有条件地调用构造函数怎么办? (虽然他们说创建单独的类是可行的)
需求结构:
超类:
public class Super
{
public Super(DTO1 dto1Object){
this.dto1Object = dto1Object;
}
public Super(DTO2 dto2Object)){
this.dto2Object = dto2Object;
}
}
派生类:
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
}
}
我应该如何实现它?
编辑:
根据以下建议以这种方式实现:
超类:
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;
}
}
派生类:
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:
根据下面的建议,这是使用instanceof 的正确方法吗?
if (create(dto1Obj) instanceof DTO1) {
//something
}
else if(create(dto2Obj) instanceof DTO2) {
//something else
}
显示以下错误:
Incompatible conditional operand types Derived and DTO1
Incompatible conditional operand types Derived and DTO2
【问题讨论】:
-
你不能在构造函数中,因为
super(...)必须是第一个语句。 -
你不能,基本上。要么你需要添加一个
Super(Object)构造函数,要么在Derived中创建一个静态工厂方法和两个单独的私有构造函数。 -
是的。只需使用静态工厂 - 根据“有效 Java”,这是一个很好的做法
标签: java constructor instanceof constructor-overloading