Inheriting from Sealed classes in MATLAB

In MATLAB, one of the class attributes (defined after classdef ) is Sealed , which means that no class can use it as a superclass (or, to be more precise) to indicate that these classes are not intended to support subclasses . " 1 ).

For example, if I try to create an instance of the class that is defined below (given table is Sealed ):

 classdef SomeLie < table end 

I would get the error 'MATLAB:class:sealed' :

 >> A = SomeLie; Error using SomeLie Class 'table' is Sealed and may not be used as a superclass. 

As I refuse to tell the machine what I can or cannot do, I would like to subclass the Sealed class , independently. How to do it in MATLAB R2017a?

It’s hard for me to believe that this system is completely tight, so I’m looking for a solution that will silence the ignored Sealed attribute (or something like that). The desired solution should work without changing any “library class definitions” to remove Sealed from them.


I tried to play with "reflection", but came to a standstill ...

 classdef SomeLie % < table properties (Access = private) innerTable table; end properties (GetAccess = public) methodHandles struct = struct(); end methods function slObj = SomeLie(varargin) slObj.innerTable = table(varargin{:}); % methodHandles = methods(slObj.innerTable); ml = ?table; ml = {ml.MethodList.Name}.'; ml = setdiff(ml,'end'); tmpStruct = struct; for indM = 1:numel(ml) tmpStruct.(ml{indM}) = str2func([... '@(varargin)' ml{indM} '(slObj.innerTable,varargin{:})']); end slObj.methodHandles = tmpStruct; end function varargout = subsref(slObj,varargin) S = struct(slObj); varargout{:} = S.methodHandles.(varargin{1}.subs)(varargin{:}); end end end 

(No need to fix the above code, I just shared)

+5
source share
1 answer

I don’t think the car is a problem, but the class designer, and of course he has good motives to seal the class. The "philosophy" of coding, part, you could "own" a class in a wrapper class without defining its tightness.

For example, the supposer Hello class is sealed and has a sayHello method (or function, if you want) that you would like to use in the inherited classes, you could define the FreeHello (public) class that contains the Hello instance. In the constructor, you create the corresponding Hello, and then you define the sayHello method, the body of which simply calls your Hello instance and forces it to execute the sayHello method (and returns the result accordingly).

To "open" a private class, you need to do this for all properties and public methods; Of course, you still cannot access private methods, but now you can subclass your wrapper class however you want.

0
source

Source: https://habr.com/ru/post/1266123/


All Articles