3
votes

In Matlab (2017b) I'm trying to implement a superclass with a yet undefined abstract property.

classdef Class_Test1
    properties (Abstract=true)
        obj
    end
end

Subclasses should then implement this property and restrict it to a certain class, e.g.:

classdef Class_Test2 < Class_Test1
    properties
        obj@double = 123;
    end
end

a = Class_Test2; now throws an error:

The property 'obj' restriction defined in class 'Class_Test2' must match
the property definition in base class 'Class_Test1'.

Is there no way to specify the class / type of obj in the implementation of the abstract class or am I missing something?

In the end I would like obj to be abstract in Class_Test1 to implement several subclasses, which will hold objects of different classes in obj.

Any help appreciated ...

2

2 Answers

1
votes

MATLAB classes are weird... or in any case very different from what you expect from a class if you've learnt about classes in any other programming language.

One aspect of MATLAB is that it's an interpreted language. Stuff is evaluated when executed, not when compiled. So code doesn't always need to make sense.

So, we can solve your issue like this:

classdef (Abstract) foo
   methods
      function c = getclass(in)
         c = class(in.obj);
      end
   end
end

The function foo.getclass seems to not make sense, since foo doesn't have a property obj. But because foo is abstract, we're never going to have an object of class foo on which we'll call the getclass method. Whenever getclass is called, it'll be a derived class. So, if we want to use this getclass method, we need to make sure that the derived class has a property obj:

classdef foo_uint8 < foo
    properties
        obj@uint8 = uint8(1);
    end
end

It is now possible to call foo_uint8.getclass:

>> a = foo_uint8;
>> a.getclass
ans =
    'uint8'
0
votes

OK, so after looking into this further it seems that this is a deliberate limitation based on the design of Matlab. I'm not too familiar with OOP in other languages but would be interested to learn if this is an general OOP fundamental or rather Matlab specific.

As a workaround I have come up with the following solution:

classdef (Abstract) Class_Test1 < handle
    properties
        Obj
    end
    properties (Abstract = true, Constant)
        ObjClass@char
    end
    methods 
        function set.Obj(obj_in,in)
            if isa(in, obj.ObjClass)
                obj_in.Obj = in;
            end
        end
    end
end

... and the implementation ...

classdef Class_Test2 < Class_Test1

    properties (Constant)
        ObjClass@char = 'double';  % Define the allowed class here ...
    end

end

I would still be interested to learn about other possible solutions.