Skip to content

faq 74383362

Billy Charlton edited this page Sep 5, 2018 · 2 revisions

How can I inherit from a MATSim core class that is final?

by Kai Nagel on 2016-07-20 15:07:48


Comments: 1


Re: How can I inherit from a MATSim core class that is final?

by Kai Nagel on 2016-07-20 15:24:05

In newer code, and newer refactorings, we have a tendency to "favor delegation/composition over inheritance".  You can search for the term in google, or read item 16 of Bloch, "Effective Java".  

Normally, such classes are behind an interface.  So if you see

public final class YyyyImpl implements Yyyy {
    @Override public aMethod(...) { ... }
 }

you can do something like

class MyYyyy implements Yyyy {
    private Yyyy delegate ;
    MyYyyy(...) {
       delegate = new Yyyy(...) ;
    }
    @Override
    public aMethod(...) {
       delegate.aMethod(...) ;
    }
 }

Most IDEs provide support for this, in eclipse for example "Source → GenerateDelegateMethods".

Once one has gotten used to it, it is not that much more difficult than plain inheritance.  A disadvantage is that classes become quite long because of the long list of delegated methods.  One also has slightly less flexibility; there is some explanation at http://matsim.org/the-book in section 46.2.1.5 "Code reorganization".  This reduced flexibility is the price one pays for better core code maintenability.

If you are unable to replace inheritance by delegation, please let us know and we will look into it.  There are, for example, not so few cases where the existing interfaces are not powerful enough to allow the above approach – and in these situations, we need to change the core code.


Clone this wiki locally