if you think this library has been useful, feel free to give any help. Don't be shy.

Click here to lend your support to: Java2word, coding for fun! and make a donation at !

Saturday, February 19, 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{

    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.


Leonardo Correa