Return different type of data from a method in java?

前端 未结 13 1507
别那么骄傲
别那么骄傲 2020-12-05 02:18
public static void main(String args[]) {
    myMethod(); // i am calling static method from main()
 }

.

public static ? myMethod(){         


        
13条回答
  •  臣服心动
    2020-12-05 03:02

    Generally if you are not sure of what value you will end up returning, you should consider using return-type as super-class of all the return values. In this case, where you need to return String or int, consider returning Object class(which is the base class of all the classes defined in java).

    But be careful to have instanceof checks where you are calling this method. Or else you may end up getting ClassCastException.

    public static void main(String args[]) {
            Object obj = myMethod(); // i am calling static method from main() which return Object
        if(obj instanceof String){
        // Do something
        }else(obj instance of Integer) {
        //do something else
         }
    

提交回复
热议问题