Pages

Saturday 19 February 2011

Java2word covariant return type

When I was studying for SCJP exam, in 2007, I had to learn a lot of things that didn't make sense and I thought that I would never use. 

Today, in my Java2word library, I utilized Covariant Return Type.

This basically is when you override some method, you can return any subtype of the original return type. Eg.:

The class ParagraphPieceStyle extends AbstractStyle and overrides the method create().

public abstract class AbstractStyle implements ISuperStylin {

    private IElement element;
   
    public void setElement(IElement element) {
        this.element = element;
    }
   
    public IElement create() {
        return this.element;
    }
   
}

public class ParagraphPieceStyle extends AbrstractStyle{

    @Override
    public ParagraphPiece create() {
        return (ParagraphPiece) super.create();
    }

}


The original return type is "IElement" but returns "ParagraphPieceStyle".The advantage of this is the flexibility to return any subtype of the original type.

this is the code without Covariant:

ParagraphPiece myParPiece01 = (ParagraphPiece) ParagraphPiece.with("...");


This is with covariant:

ParagraphPiece myParPiece01 = ParagraphPiece.with("..."); 

Now I don't need to do a type cast (downcast) of the type.




https://code.google.com/p/java2word/


cheers

Leonardo Correa

No comments:

Post a Comment