5

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 ?

1
  • This is no the only issue for abstract classes. The same problem is with base classes (virtual)
    – Vlad
    Commented Apr 17, 2013 at 15:19

1 Answer 1

1

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;
    }
}
2
  • 1
    Thanks. I've already implemented that way. Doesn't this approach violate DRY principle ?
    – Vlad
    Commented Apr 17, 2013 at 15:55
  • 1
    for classes that only add behavour it does tend to seem like a lot of boiler plate code, but if your classes have additional state, that needs initializing somewhere, this is a common issue in java/c#/apex and a lot of other OO languages.
    – superfell
    Commented Apr 17, 2013 at 16:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .