Can abstract classes have non-default constructors?

Abstract class:

public abstract class FilterCriterionAbstract 
{   
    protected Object leftComparableElement;
    protected Object rightComparableElement;

    public FilterCriterionAbstract()
    {

    } 

    public FilterCriterionAbstract(Object leftComparableElement, Object rightComparableElement) 
    {   
            this.leftComparableElement = leftComparableElement;
            this.rightComparableElement = rightComparableElement;
    }

    abstract Boolean eval();
}

Concrete class:

public with sharing class FilterCriterionEquals extends FilterCriterionAbstract
{
    public Boolean eval()
    {
        return leftComparableElement == rightComparableElement;
    }
}

Test class:

@isTest
private class FilterCriteriaTest {

    static testMethod void myUnitTest() {

        Integer i = 1;
        Integer i2 = 2;

        SL_FilterCriterionAbstract c = new SL_FilterCriterionEquals((Object)i, (Object)i2);  

        //System.assert(c.eval());       
    }


}

Without default constructor in abstract class I am getting following exception:

line 1, column 27: Parent class has no 0-argument constructor for implicit construction

With default constructor (as in my example):

Save error: Constructor not defined: [FilterCriterionEquals].<Constructor>(Object, Object)  FilterCriteriaTest.cls  .../src/classes line 30 Force.com save problem

Could someone explaine to me that behaviour, please ?

Answer

Your concrete class needs a constructor that calls the correct base class constructor, e.g.

public with sharing class FilterCriterionEquals extends FilterCriterionAbstract
{
    public FilterCriterionEquals(Object lhs, Object rhs) {
        super(lhs, rhs);
    }

    public Boolean eval()
    {
        return leftComparableElement == rightComparableElement;
    }
}

Attribution
Source : Link , Question Author : Vlad , Answer Author : superfell

Leave a Comment