Bharath
Bharath

Reputation: 169

How can I return objects of different type from a single function?

I need to return objects of different classes in a single method using the keyword Object as the return type

public class ObjectFactory {
public static Object assignObject(String type) {

    if(type.equalsIgnoreCase("abc")){
         return new abcClass();
    } else if(type.equalsIgnoreCase("def")) {
         return new defClass();
    } else if(type.equalsIgnoreCase("ghi")) {
         return new ghiClass();
    }
    return null;
    }
}

and in another class I am trying to get the objects as

public class xyz{
public void get(){
    Object obj=(abcClass)ObjectFactory.assignObject("abc");
}
}

How can I access the methods in abcClass using the obj object??

Upvotes: 0

Views: 1644

Answers (3)

Pherion
Pherion

Reputation: 155

I would suggest as one of the commentators on your initial post did. That is, refactor this to use an interface.

Your classes AbcClass, DefClass, and GhiClass, could all implement an interface, lets call it Letters. You can then define a class called LettersFactory, with the method createLetters. At this point, I'd also recommend changing your hard coded string identifiers into an enumeration. For instance:

public enum LetterTypes { ABC, DEF, GHI }

You're factory method can then accept this enumeration, and you have no fears of getting invalid values. The factory method can also return the type Letters (the interface) and you have a more specific version of Object (which is good).

Finally, if you need to determine these types on the fly, you can have a method defined in Letters (forcing all children to implement it) called getType() which returns the LetterTypes enumeration for the class that is implemented.

You could also use the instanceof operator to determine which class you have.

Cheers, Frank

Upvotes: 1

AnkeyNigam
AnkeyNigam

Reputation: 2820

You can use this as a refrence :-

public Object varyingReturnType(String testString ){
    if(testString == null)
    return 1;
    else return testString ;
} 

Object o1 = varyingReturnType("Lets Check String");
if(  o1 instanceof String) //return true
 String now = (String) o1;
Object o2 = varyingReturnType(null);
if(  o2 instanceof Integer) //return true
 int i = (Integer)o2;

So similarly you can use your own conditions along with the instanceof operator and can cast it to get the actual object type from Object type.

Upvotes: 0

Eran
Eran

Reputation: 394146

Your current code will throw an exception if assignObject returns an instance that is not an abcClass, so you can change the type of obj to absClass :

public void get(){
    abcClass obj=(abcClass)ObjectFactory.assignObject("abc");
}

Upvotes: 1

Related Questions