simar
simar

Reputation: 1822

is it possible assign different return type for method

My idea is that there is a validator interface, which has method getRealValue(). The return value depends on field, it could be String, Integer or Long values.

My chances are:

  1. I can do assign return type as Object and use casting every time after I called this method. (RuntimeError if wrong casting happened).

  2. I can use generic an pass return type to validator when instantiate it (and I still have to use casting but inside method getRealValue and only once). Still RuntimeError if I will forget to pass return type or pass wrong type.

If there is a way I can store return type inside validator and use it?

Upvotes: 3

Views: 174

Answers (1)

Mena
Mena

Reputation: 48404

For your 1st point, there is no way around getting a ClassCastException at runtime in case of an inappropriate cast.

In your second case you won't need to cast, see example here:

public interface Foo<T> {
    public T getValue(); 
}

... then somewhere else:

public class Blah<T> implements Foo<T> {
    @Override
    public T getValue() {
        // TODO write the code
        // note that because of type erasure you won't know what type T is here
        return null;
    }
}

... then, somewhere else:

Blah blah1 = new Blah<String>();
String s = blah1.getValue();
Blah blah2 = new Blah<Long>();
// etc.

Finally, here's some literature for you:

Upvotes: 10

Related Questions