1

i want to return class objects but in generic manner. Comsider lot of if conditions and in each i am creating an object of one class; but want to return at last using only one return statement.

How to do that ??

1 Answer 1

2

The easy (but fairly limited) way would be to have your method simply return an Object type:

Object val = yourMethod();

public Object yourMethod() {
   Object returnObject = null;
   if(conditionA){
        returnObject = new Class1();
   } else if(conditionB) {
        returnObject = new Class2();
   }    
   return returnObject;
}

However, if you want to return an object of a particular 'blue-print', you might consider using an Interface. This will allow you to define methods so that your implementing classes will implement them so you can call them easily in consuming code. For example:

public interface MyInterface {
   void execute();
}

public class Class1 implements MyInterface {
    public void execute() {
        // do something Class1 specific
    }
}

public class Class2 implements MyInterface {
    public void execute() {
        // do something Class2 specific
    }
}

Then, you could change the method above to be a bit more specific:

MyInterface val = yourMethod();
val.execute();

public Object yourMethod() {
   MyInterface returnObject = null;
   if(conditionA){
        returnObject = new Class1();
   } else if(conditionB) {
        returnObject = new Class2();
   }
   return returnObject;
}
8
  • i am sorry i am not getting it.
    – codeath
    Sep 2, 2014 at 10:42
  • Did you mean to say something about the code snippet? Sep 2, 2014 at 10:44
  • ` public static Object createBatchObj(String sObjName,String mWareStatus) { String status = null; Object batchObj = null; if(sObjName == 'Account' && mWareStatus == 'Down') { batchObj = new batchUpdateAccount_MwareDown(); } if(sObjName == 'Account' && mWareStatus == 'Up') { } else { status = 'Wrong value entered'; } return batchObj; }`
    – codeath
    Sep 2, 2014 at 10:47
  • this one is compiling fine.....but i think batchObj is not getting updated and usual null value will be returned...is it so??
    – codeath
    Sep 2, 2014 at 10:48
  • It would depend on your IF statements, looks to me like if SObjName is not 'Account' and mWareStatus is not 'Down' batchObj will always be null. Sep 2, 2014 at 10:52

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .