implementing abstract methods in matlab

1.7k views Asked by At

I'm new to MATLAB OOP. I have an abstract class defining an abstract method in my matlab path. I have a subclass named SubAbsClass in a subfolder named @SubAbsClass. I cannot create an object of the subclass after implementing the abstract method in the subclass. Here's my SubAbsClass implementation:

classdef SubAbsClass < AbsClass

    properties
        O1
    end

methods
        function obj=SubAbsClass(a,b)
            obj.O1=absMethod(a,b);
        end
    end
    methods (Static)

        function out = absMethod(a,b)
            out = a + b;
        end
    end
end

and my abstract class implementation is:

classdef AbsClass
    methods(Abstract, Static)
        result = absMethod
    end
end

when I try to create an object in the MATLAB path (the abstract class is in the MATLAB path), I get an error. I have tried many configurations and searched the matlab oop document, and also the web including stackoverflow but unfortunately couldn't find an example to implement. I appreciate your help

>> clear all; clear classes;
>> obj=SubAbsClass(5,2)
Undefined function 'absMethod' for input arguments of type 'double'.

Error in SubAbsClass (line 11)
            obj.O1=absMethod(a,b);
1

There are 1 answers

0
TroyHaskin On BEST ANSWER

Within a method, Matlab considers non-dot references to be calls to local functions (defined outside the classdef block within the class file) or to a function somewhere on the Matlab path following the usual look-up rules.

So you need to call the Static method via the instance obj in the constructor:

methods
    function obj = SubAbsClass(a,b)
        obj.O1 = obj.absMethod(a,b);
    end
end

One little caveat to the above is that non-Static methods also have a functional form. So if the method was not Static, this notation would also work

methods
    function obj = SubAbsClass(a,b)
        obj.O1 = absMethod(obj,a,b);
    end
end

Which, I think, is almost equivalent to the dot notation, although it has been said to be "generally" faster (albeit, that was four years ago).

Here are the details for ordinary method invocation and Static method invocation.