Return different type of data from a method in java?

前端 未结 13 1491
别那么骄傲
别那么骄傲 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:14

    I just want to put my view

    So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.

    public interface GenericReturnType{
        public static RETURN_TYPE enum{
            MACHINE, PERSON;    
        }
        public RETURN_TYPE getReturnType();
    }
    
    public class PersonReturnType implements GenericReturnType{
        // CONSTRUCTORS //
    
        // GETTRE AND SETTER //
    
        public RETURN_TYPE getReturnType(){
            return PERSON;
        }
        public String getAddress(){
            return something;
        }
    }
    
    public class MachineReturnType implements GenericReturnType{
        // CONSTRUCTORS //
    
        // GETTRE AND SETTER //
    
        public RETURN_TYPE getReturnType(){
            return MACHINE;
        }
        public String getManufatureName(){
            return something;
        }
    }
    
    
    public class TestService{
        public GenericReturnType getObject(// some input //){
            GenericReturnType obj ;
            if(// some code //){
                obj = new  PersonReturnType();
                // some code //
            }
            if(// some code //){
                obj = new  MachineReturnType();
                // some code //
            }
            return obj;
        }
    }
    
    public class TestDriver{
        TestService service = new TestService();
        GenericReturnType genObj = TestService.getObject(// some input //);
        if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
            // SOME CODE // 
        }
        if(genObj.getReturnType() == RETURN_TYPE.PERSON){
            // SOME CODE // 
        }
    }
    

提交回复
热议问题