Method accepting two different types as parameter

前端 未结 8 1838
無奈伤痛
無奈伤痛 2020-12-13 00:39

I am writing a method that should accept as its parameter an object of one of two types which do not share a parent type other than Object. For example, the types are Dreams

相关标签:
8条回答
  • 2020-12-13 01:20

    How about something as simple as this?

    utterlyDestroy(Object parameter) {    
        if(parameter instanceOf Dreams){  
            Dream dream = (Dreams)parameter;  
            dream.crush();
            //Here you can use a Dream 
        }  
        else if(parameter instanceOf Garlic){  
           Garlic garlic = (Garlic)parameter;   
            //Here you can use a Garlic  
           garlic.crush();  
       }
    } 
    

    If the utterlyDestroy is too complex and big and you just want to call the crush then this does what you want

    0 讨论(0)
  • 2020-12-13 01:21

    As I'm using :

    void fooFunction(Object o){
    Type1 foo=null;
    if(o instanceof Type1) foo=(Type1)o;
    if(o instanceof Type2) foo=((Type2)o).toType1();
    // code
    }
    

    But that only works if Type2 can be converted to Type1

    0 讨论(0)
提交回复
热议问题