lundi 12 juin 2017

Generic parent object cannot be returned as child without cast

This question might resemble cast the Parent object to Child object in C# but it is about C# and I have a question about Java.

I am also aiming to make a generic builder. The generic builder should only build the parts of the abstract object and the children all manage the induvidual implementations of the abstract class.

class GenericBuilder<B extends GenericBuilder>
{
     //lots of build methods
     public B lastBuildingMethodInTheChain(Object someValue)
     {
          //assignment
          return this;//<-- is not allowed!
     }
}

But when I put in a cast:return (B) this; it is fine. I am mostly just wondering if there is a clean way to make the cast obsolete. Thank you!

Aucun commentaire:

Enregistrer un commentaire