【发布时间】:2020-02-25 13:56:28
【问题描述】:
要求:-
在 getDetails 方法中,如果传递了 Customclass 类型的对象 B,那么我们将调用 getStatus 方法,该方法以 Customclass 作为参数。 现在,我们需要让参数同时接受 string/ customclass 类型,
so if it is string, then we are directly getting the value so need not to call getStatus method
And if it of type **customclass**, then we need to invoke getStatus
在我现有的项目中,我们从多个地方调用 getDetails,而 getDetails 是一个冗长的方法,因此重载成本太高,会导致代码重复
请提出其他方法
我有类似下面的代码:-
getDetails(Strig a, Customclass B) {
//lengthy calculation long method
String status = getStatus(B)
//lengthy calculation long method
}
我想让它像下面这样:-
getDetails(Strig a, Customclass B || String B) {
//lengthy calculation long method
String status;
If(B of type String) {
status = B;
} else {
status = getStatus(B)
}
//lengthy calculation long method
}
【问题讨论】:
-
您可以创建一个自定义类作为 Enum,在这种情况下您可以涵盖这两种情况。
-
您的建议如何?它是否需要我只在一个地方进行更改,还是我需要在我调用它的任何地方重复代码?有示例代码吗?
标签: java generics polymorphism overloading