Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics - method return type as extending class

Tags:

java

generics

I am trying to achieve this in Java 6 :

abstract class CurrClass{
    public <T extends CurrClass> T setField (String str) {
        return this;
    }
}

Compiler complains with error : Type mismatch: cannot convert from CurrClass to T.

Adding cast works, with warning :"return (T) this;"

Is there a cleaner syntax to do this? Why is the cast needed?

like image 851
Paddy Avatar asked Aug 26 '26 18:08

Paddy


2 Answers

The return type is more restrictive than the object being returned. That's why the compiler generates the error (and subsequent warning). Consider this scenario:

class A extends CurrClass {}
class B extends CurrClass {}

...

A myObject = new B().setField("stringhere");

This is perfectly legal in your setup, but will result in a ClassCastException.

That's why usually we only return a more restrictive type than the signature calls for.

like image 159
blgt Avatar answered Aug 28 '26 09:08

blgt


Why is the cast needed?

Because this is the CurrClass and the method setField() want to return a extending class of it.

Super super = new Sub();   //it's fine, no casting is needed
Sub sub = new Super();     //error!! -->what you do

Is there a cleaner syntax to do this?

If you want to SubClass s = super.setField("");, you have to cast.

But we often do Super s = sub.setField(""); for polymorphism can bring us convenience.

like image 25
Tony Avatar answered Aug 28 '26 07:08

Tony



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!