Method accepting two different types as parameter

前端 未结 8 1862
無奈伤痛
無奈伤痛 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:12

    Simply use method overloading.

    public void utterlyDestroy(Dreams parameter) {
        parameter.crush();
    }
    
    public void utterlyDestroy(Garlic parameter) {
        parameter.crush();
    }
    

    If you want to support more than these two types in the same way, you can define a common interface for them all and use generics.

提交回复
热议问题