我有以下三个类(class)。
SuperClass.java
SubClass1 extends SuperClass
SubClass2 extends SuperClass
我有一个方法,它将接受 SuperClass
类型的方法参数.
getResult(SuperClass request){
//Here the request can be of SubClass1 type or SubClass2 type.
}
这里是request
可以是 SubClass1
输入或 SubClass2
类型。
内部getResult()
基于请求类型的方法我需要做一些逻辑。
要找出我可以使用的类型instanceof
运算符如下。
if(request instanceof SubClass1){
//do something
}else if(request instanceof SubClass2){
//dosomething
}
有没有最好的方法来找出请求的类型?
谢谢!
最佳答案
尽量避免 instanceof
关键字。
The reason instanceof is discouraged is that it's not OOP. There should be no reason for the caller/user of an object to know which concrete class it is an instance of beyond which type the variable it is declared as. If you need different behavior in subclasses add a method and implement them differently.
基本方式:我会写这样的内容:
enum Types{ SUB_1, SUB_2 }
public class SubClass1 extends SuperClass{
public Types type = Types.SUB_1;
}
public class SubClass2 extends SuperClass{
public Types type = Types.SUB_2;
}
和:
if(Types.SUB_1 == request.type){
//do something
}else if(Types.SUB_2 == request.type){
//do something
}
正确的方式(从我的角度来看)我会在你的情况下使用多态性。
多态性 - 发送到不同对象的相同消息会导致相关行为 接收消息的对象的性质。
意思是:
public interface SuperClassItf{
public void doStuff();
}
public class SubClass1 extends SuperClassItf{
public void doStuff(){
// do 1
}
}
public class SubClass2 extends SuperClassItf{
public void doStuff(){
// do 2
}
}
主要
getResult(SuperClassItf request){
request.doStuff(); //polymorphic method call
}
关于java - 决定请求类的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19420483/