Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it possible assign different return type for method

Tags:

java

generics

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?

like image 725
simar Avatar asked May 26 '26 02:05

simar


1 Answers

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:

  • Generics in Java
  • Inheritance in Java (has a section on casting)
like image 137
Mena Avatar answered May 27 '26 14:05

Mena



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!