{"id":1073,"date":"2014-12-17T13:10:12","date_gmt":"2014-12-17T18:10:12","guid":{"rendered":"https:\/\/blogs.mathworks.com\/loren\/?p=1073"},"modified":"2016-08-04T09:14:55","modified_gmt":"2016-08-04T14:14:55","slug":"subclasses-in-matlab","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/loren\/2014\/12\/17\/subclasses-in-matlab\/","title":{"rendered":"Subclasses in MATLAB"},"content":{"rendered":"<div class=\"content\"><!--introduction--><p>I'm pleased to have Dave Foti back for a discussion of subclassing and class hierarchies in MATLAB.  Dave manages the group responsible for object-oriented programming features in MATLAB.<\/p><p>In computer science, a class represents a set of objects that share a common definition, usually including data and functions or behaviors.  A subclass represents a subset of objects that share a more specific definition usually by adding or specializing data and\/or functions defined in a superclass.  In practice subclassing has been used to reuse functionality for a new and more specialized purpose. In recent years, this usage has become largely discouraged due to the tendency for introducing errors in programs that reuse superclasses (often called base classes) for applications not anticipated by the original class. A class author hides the inner workings of a class to make the class useful as an abstract representation.  That same hiding of details can also hinder the ability of a programmer to anticipate how the class will function in a new role.  Let's explore some cases where subclassing does make sense in MATLAB and how to avoid some common programming pitfalls.<\/p><!--\/introduction--><h3>Contents<\/h3><div><ul><li><a href=\"#1511d357-b744-4fa2-9d73-082997d604a1\">Modeling Physical Systems<\/a><\/li><li><a href=\"#f7be8ee8-d80d-4cbd-a0ba-1f9f3c24496f\">Systems of Abstract Data Structures<\/a><\/li><li><a href=\"#f4cf534e-bed8-457d-a924-063726c8a18a\">Mixins<\/a><\/li><li><a href=\"#2d18db35-a21d-4aed-9a77-d28beb1a3436\">Other Patterns<\/a><\/li><li><a href=\"#3c85ea36-4240-4199-b66d-db980992a1ea\">Design Considerations<\/a><\/li><li><a href=\"#040821be-9ea6-458c-8741-d3ca891841a9\">Preventing Unexpected Subclassing<\/a><\/li><li><a href=\"#93be9120-d155-47df-929a-06c4803640ad\">References<\/a><\/li><\/ul><\/div><h4>Modeling Physical Systems<a name=\"1511d357-b744-4fa2-9d73-082997d604a1\"><\/a><\/h4><p>One of the most obvious uses for subclassing in MATLAB is a situation requiring a model of a real physical system that has already been classified.  In such a situation, it might make sense to build a software model that closely resembles the real physical classification system. For example, one could create objects based on the Standard Model of particle physics <a href=\"http:\/\/en.wikipedia.org\/wiki\/Standard_Model\">[1]<\/a>.  In this way, the classification system already exists and can simply be represented in software.  There is still design work to be done in how best to represent a physical system in software for a specific purpose, but all the classes can be built at roughly the same time by the same person or team and thus avoid the pitfalls of reusing an existing class later on after its details have been forgotten. Here is what a superclass might look like for elementary particles in the Standard Model:<\/p><pre class=\"codeinput\">type <span class=\"string\">ElemParticle<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef ElemParticle\r\n    % Intrinsic properties of the particle\r\n    properties(SetAccess = immutable)\r\n        Spin\r\n        Charge\r\n        Mass\r\n    end\r\n    \r\n    % State variables for a particular particle\r\n    properties\r\n        Position = [0 0 0];\r\n        Velocity = [0 0 0];\r\n    end\r\n    \r\n    methods\r\n        function p = ElemParticle(spin, charge, mass)\r\n            p.Spin = spin;\r\n            p.Charge = charge;\r\n            p.Mass = mass;\r\n        end\r\n    end\r\nend\r\n<\/pre><p>We can then create subclasses for fermions and bosons:<\/p><pre class=\"codeinput\">type <span class=\"string\">Fermion<\/span>\r\ntype <span class=\"string\">Boson<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef Fermion &lt; ElemParticle\r\n    methods \r\n        function p = Fermion(charge, mass)\r\n            p@ElemParticle(.5, charge, mass);\r\n        end\r\n    end\r\nend\r\n\r\nclassdef Boson &lt; ElemParticle\r\n    methods\r\n        function p = Boson(mass)\r\n            p@ElemParticle(0, 0, mass);\r\n        end\r\n    end\r\nend\r\n\r\n<\/pre><p>We can divide the Fermions into Leptons and Quarks:<\/p><pre class=\"codeinput\">type <span class=\"string\">Lepton<\/span>\r\ntype <span class=\"string\">Quark<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef Lepton &lt; Fermion\r\n    methods\r\n        function p = Lepton(charge, mass)\r\n            p@Fermion(charge, mass);\r\n        end\r\n    end\r\nend\r\n\r\nclassdef Quark &lt; Fermion\r\n    properties\r\n        Color\r\n    end\r\n    \r\n    methods\r\n        function p = Quark(charge, mass, color)\r\n            p@Fermion(charge, mass);\r\n            p.Color = color;\r\n        end\r\n    end\r\nend\r\n<\/pre><p>In the above example, the superclasses and subclasses were designed as a single collection of classes so there is no need for superclasses to anticipate the needs of unknown future subclasses.  Any future evolution of the superclasses needs to consider the whole system, but it is a bounded list of classes.<\/p><h4>Systems of Abstract Data Structures<a name=\"f7be8ee8-d80d-4cbd-a0ba-1f9f3c24496f\"><\/a><\/h4><p>Even if one is not modeling a physical system with an existing classification model that makes sense in software, there are still other examples where a system of classes can be designed at roughly the same time to fulfill some purpose such as managing a variety of data formats or anaysis techniques.  For example, we might have a need to visualize some data as points.  We might know that we have two kinds of data sets: one that is two-dimensional and one that is three-dimensional.  We design a class that handles 2-D data and a sub-class that adds support for a third dimension.  Here is what the 2-D class looks like:<\/p><pre class=\"codeinput\">type <span class=\"string\">PointList<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef PointList\r\n    properties\r\n        X\r\n        Y\r\n    end\r\n    \r\n    methods(Sealed)\r\n        function show(pc)\r\n            figure;\r\n            data = getData(pc);\r\n            opts = {'+', 'MarkerSize', 3};\r\n            if numel(data) == 3\r\n                plot3(data{:},opts{:});\r\n            else\r\n                plot(data{:},opts{:});\r\n            end\r\n        end\r\n    end\r\n    \r\n    methods(Access = protected)\r\n        function data = getData(pc)\r\n            data = {pc.X, pc.Y};\r\n        end\r\n    end\r\nend\r\n<\/pre><p>Because we know that we want to support 3-D data, we design our plotting routine to be able to handle 2-D or 3-D data.  This is an advantage of knowing about all the subclasses in the beginning.  Then when we write the 3-D subclass:<\/p><pre class=\"codeinput\">type <span class=\"string\">PointList3D<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef PointList3D &lt; PointList\r\n    properties\r\n        Z\r\n    end\r\n    \r\n    methods(Access = protected)\r\n        function data = getData(pc)\r\n            data = {pc.X, pc.Y, pc.Z};\r\n        end\r\n    end\r\nend\r\n<\/pre><p>it is very easy to support 3-D plots without rewriting the whole show method.  Here we produce a 3-D point cloud for the 3rd harmonic of the L-shaped membrane:<\/p><pre class=\"codeinput\">L = membrane(3);\r\n[X, Y] = meshgrid(1:length(L), 1:length(L));\r\npts = PointList3D;\r\npts.Z = L(:);\r\npts.X = X(:);\r\npts.Y = Y(:);\r\nshow(pts)\r\n<\/pre><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2014\/subclassblog_01.png\" alt=\"\"> <h4>Mixins<a name=\"f4cf534e-bed8-457d-a924-063726c8a18a\"><\/a><\/h4><p>Another good reason to use subclassing is when a superclass is designed specifically for reuse.  A common design pattern <a href=\"http:\/\/en.wikipedia.org\/wiki\/Design_pattern_(computer_science)\">[2]<\/a> is called the mixin pattern <a href=\"http:\/\/en.wikipedia.org\/wiki\/Mixin\">[3]<\/a>.  In this pattern a class is often used to implement one specialized piece of functionality.  This class represents all objects that have this common functionality even though such classes may do other things very differently.  A mixin class should expect nothing of a subclass except that it uses the mixin functionality.  A common example of a mixin class in MATLAB is the class called <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.customdisplay-class.html\"><tt>matlab.mixin.CustomDisplay<\/tt><\/a> which is used to customize the MATLAB default object display while retaining appropriate consistency with other objects.  Here is an example of this mixin being used on our <tt>ElemParticle<\/tt> superclass. To separate this version from the previous example, I've put the new version of the classes in a package called <tt>particle<\/tt>.<\/p><pre class=\"codeinput\">type <span class=\"string\">+particle\/ElemParticle<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef ElemParticle &lt; matlab.mixin.CustomDisplay\r\n    % Intrinsic properties of the particle\r\n    properties(SetAccess = immutable)\r\n        Spin\r\n        Charge\r\n        Mass\r\n    end\r\n    \r\n    % State variables for a particular particle\r\n    properties\r\n        Position = [0 0 0];\r\n        Velocity = [0 0 0];\r\n    end\r\n    \r\n    methods\r\n        function p = ElemParticle(spin, charge, mass)\r\n            p.Spin = spin;\r\n            p.Charge = charge;\r\n            p.Mass = mass;\r\n        end\r\n    end\r\n    \r\n    methods(Access = protected, Sealed)\r\n        function propgroups = getPropertyGroups(p)\r\n            propgroups = matlab.mixin.util.PropertyGroup;\r\n            propgroups(1).Title = 'Intrinsic';\r\n            propgroups(1).PropertyList = getIntrinsicPropertyNames(p);\r\n            propgroups(2).Title = 'State';\r\n            propgroups(2).PropertyList = {'Position','Velocity'};\r\n        end\r\n    end\r\n    \r\n    methods(Access = protected)\r\n        function pnames = getIntrinsicPropertyNames(~)\r\n            pnames = {'Spin','Charge','Mass'};\r\n        end        \r\n    end\r\nend\r\n<\/pre><p>Note that whenever functionality is designed for a superclass such as this, it is important to implement the functionality for the whole class of objects including all instances of subclasses.  Thus, the display should not just show what is common to <tt>ElemParticle<\/tt>, but should provide for specialization in subclasses.  In this case, we add one method that can be specialized by subclasses to provide lists of intrinsic properties. Since we know about all the subclasses, we don't need to worry about what kinds of property groups a future subclass might need. We can see why it is important for superclasses to be designed with the knowledge that subclasses will be created and why it is very helpful if the subclasses are already known during this design.  In this case, we know the family of subclasses of <tt>ElemParticle<\/tt> and thus we know that they will sometimes need to add new properties, but not whole new groups of properties.  We choose the right amount of generality in the superclass so that each subclass can specialize display with minimal effort.  In fact <tt>Quark<\/tt> is the only particle that needs additional code as shown here:<\/p><pre class=\"codeinput\">type <span class=\"string\">+particle\/Quark<\/span>\r\n<\/pre><pre class=\"codeoutput\">\r\nclassdef Quark &lt; particle.Fermion\r\n    properties\r\n        Color\r\n    end\r\n    \r\n    methods\r\n        function p = Quark(charge, mass, color)\r\n            p@particle.Fermion(charge, mass);\r\n            p.Color = color;\r\n        end\r\n    end\r\n    \r\n    methods(Access = protected)\r\n        function pnames = getIntrinsicPropertyNames(p)\r\n            pnames = [getIntrinsicPropertyNames@particle.Fermion(p), 'Color'];\r\n        end\r\n    end\r\nend\r\n<\/pre><p>We can now create and display an electron and a top quark:<\/p><pre class=\"codeinput\">e = particle.Lepton(-1, 5.11e-4)\r\n<\/pre><pre class=\"codeoutput\">e = \r\n  Lepton with properties:\r\n\r\n   Intrinsic\r\n      Spin: 0.5\r\n    Charge: -1\r\n      Mass: 0.000511\r\n   State\r\n    Position: [0 0 0]\r\n    Velocity: [0 0 0]\r\n<\/pre><pre class=\"codeinput\">t = particle.Quark(2\/3, 173.07, <span class=\"string\">'red'<\/span>)\r\n<\/pre><pre class=\"codeoutput\">t = \r\n  Quark with properties:\r\n\r\n   Intrinsic\r\n      Spin: 0.5\r\n    Charge: 0.66667\r\n      Mass: 173.07\r\n     Color: 'red'\r\n   State\r\n    Position: [0 0 0]\r\n    Velocity: [0 0 0]\r\n<\/pre><h4>Other Patterns<a name=\"2d18db35-a21d-4aed-9a77-d28beb1a3436\"><\/a><\/h4><p>Other common patterns where classes are designed for unbounded subclassing include interfaces <a href=\"http:\/\/en.wikipedia.org\/wiki\/Interface_(computer_science)\">[4]<\/a> and frameworks <a href=\"http:\/\/en.wikipedia.org\/wiki\/Framework_(computer_science)\">[5]<\/a>.  Interface classes define how two pieces of code can interact with each other without actually defining how those interactions are accomplished.  Because MATLAB is a dynamically typed language, it is possible to write functions to an interface that isn't actually defined as a class.  For example many functions in MATLAB can work with any object that implements the <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/size.html\"><tt>size<\/tt><\/a>, <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/subsref.html\"><tt>subsref<\/tt><\/a>, and <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/subsasgn.html\"><tt>subsasgn<\/tt><\/a> functions to perform reshaping operations on arrays.  In some cases, it may be useful to define interfaces explicitly so that it is easier to determine what kinds of objects will work with a particular function and so that it is easier to see the capabilities of a class in the explicit interfaces it supports.<\/p><h4>Design Considerations<a name=\"3c85ea36-4240-4199-b66d-db980992a1ea\"><\/a><\/h4><p>When designing a class for extension in the future, it is a good idea to think about how subclasses might restrict evolution of the base class. Some questions to consider are:<\/p><div><ul><li>Is it clear that there will be no need to add any properties or methods to the base class in the future?<\/li><li>Is it clear that only internal implementation details will need to change over time and not the fundamental meaning and behavior of the class?<\/li><\/ul><\/div><p>When designing methods in the base class, it is important to consider how subclasses will reuse and as necessary adapt these methods while maintaining the principle that subclass instances can be substituted for base class instances <a href=\"http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle\">[6]<\/a>.  Some questions to ask are:<\/p><div><ul><li>What methods might need to be specialized?<\/li><li>How can base class methods be best organized to allow subclasses to reuse as much base class implementation as possible?<\/li><li>Are there ways to better ensure that subclasses still behave consistently with the intended behavior of the class?<\/li><\/ul><\/div><p>Once a class has been presented as a base class, its fundamental definition should not change or else subclasses could become invalid or produce erroneous results.  The new or changed behaviors and capabilities may not be appropriate for all subclasses.  The subclass authors could not possibly anticipate changes to the superclass when the subclasses were created.  This is one of the reasons for adhering to the open\/closed design principle <a href=\"http:\/\/en.wikipedia.org\/wiki\/Open\/closed_principle\">[7]<\/a>.<\/p><h4>Preventing Unexpected Subclassing<a name=\"040821be-9ea6-458c-8741-d3ca891841a9\"><\/a><\/h4><p>Given the importance of considering how a class will be extended by subclasses, MATLAB provides ways to signal that a class wasn't designed for subclassing.  Classes with the Sealed attribute set can't be used as superclasses.  If an entire class hierarchy was designed together but not intended for extension with additional subclasses, then it can be sealed using the Sealed attribute on the leaf classes and the AllowedSubclasses attribute on the superclasses.  MathWorks will at times seal classes or class hierarchies of widely used classes to indicate that these classes have not been designed to support subclasses.<\/p><p>These are some thoughts on subclassing in MATLAB, but I'd like to hear your thoughts as well.  Have you used any of the mixin MATLAB classes like <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.customdisplay-class.html\"><tt>matlab.mixin.CustomDisplay<\/tt><\/a> or <a href=\"https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.heterogeneous-class.html\"><tt>matlab.mixin.Heterogeneous<\/tt><\/a>?  Do you have suggestions for mixin classes that you would like to see in MATLAB? <\/p><h4>References<a name=\"93be9120-d155-47df-929a-06c4803640ad\"><\/a><\/h4><div><ol><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Standard_Model\">http:\/\/en.wikipedia.org\/wiki\/Standard_Model<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Design_pattern_(computer_science)\">http:\/\/en.wikipedia.org\/wiki\/Design_pattern_(computer_science)<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Mixin\">http:\/\/en.wikipedia.org\/wiki\/Mixin<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Interface_(computer_science)\">http:\/\/en.wikipedia.org\/wiki\/Interface_(computer_science)<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Framework_(computer_science)\">http:\/\/en.wikipedia.org\/wiki\/Framework_(computer_science)<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle\">http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle<\/a><\/li><li><a href=\"http:\/\/en.wikipedia.org\/wiki\/Open\/closed_principle\">http:\/\/en.wikipedia.org\/wiki\/Open\/closed_principle<\/a><\/li><\/ol><\/div><script language=\"JavaScript\"> <!-- \r\n    function grabCode_0a1da298a1364295b8588f939334a2f8() {\r\n        \/\/ Remember the title so we can use it in the new page\r\n        title = document.title;\r\n\r\n        \/\/ Break up these strings so that their presence\r\n        \/\/ in the Javascript doesn't mess up the search for\r\n        \/\/ the MATLAB code.\r\n        t1='0a1da298a1364295b8588f939334a2f8 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\r\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 0a1da298a1364295b8588f939334a2f8';\r\n    \r\n        b=document.getElementsByTagName('body')[0];\r\n        i1=b.innerHTML.indexOf(t1)+t1.length;\r\n        i2=b.innerHTML.indexOf(t2);\r\n \r\n        code_string = b.innerHTML.substring(i1, i2);\r\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\r\n\r\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \r\n        \/\/ in the XML parser.\r\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\r\n        \/\/ doesn't go ahead and substitute the less-than character. \r\n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\r\n\r\n        copyright = 'Copyright 2014 The MathWorks, Inc.';\r\n\r\n        w = window.open();\r\n        d = w.document;\r\n        d.write('<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add copyright line at the bottom if specified.\r\n        if (copyright.length > 0) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\\n');\r\n\r\n        d.title = title + ' (MATLAB code)';\r\n        d.close();\r\n    }   \r\n     --> <\/script><p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><br><a href=\"javascript:grabCode_0a1da298a1364295b8588f939334a2f8()\"><span style=\"font-size: x-small;        font-style: italic;\">Get \r\n      the MATLAB code <noscript>(requires JavaScript)<\/noscript><\/span><\/a><br><br>\r\n      Published with MATLAB&reg; R2014b<br><\/p><\/div><!--\r\n0a1da298a1364295b8588f939334a2f8 ##### SOURCE BEGIN #####\r\n%% Subclasses in MATLAB\r\n% I'm pleased to have Dave Foti back for a discussion of subclassing and\r\n% class hierarchies in MATLAB.  Dave manages the group responsible for\r\n% object-oriented programming features in MATLAB.\r\n%\r\n% In computer science, a class represents a set of objects that share a\r\n% common definition, usually including data and functions or behaviors.  A\r\n% subclass represents a subset of objects that share a more specific\r\n% definition usually by adding or specializing data and\/or functions\r\n% defined in a superclass.  In practice subclassing has been used to reuse\r\n% functionality for a new and more specialized purpose. In recent years,\r\n% this usage has become largely discouraged due to the tendency for\r\n% introducing errors in programs that reuse superclasses (often called base\r\n% classes) for applications not anticipated by the original class. A class\r\n% author hides the inner workings of a class to make the class useful as an\r\n% abstract representation.  That same hiding of details can also hinder the\r\n% ability of a programmer to anticipate how the class will function in a\r\n% new role.  Let's explore some cases where subclassing does make sense in\r\n% MATLAB and how to avoid some common programming pitfalls.\r\n%% Modeling Physical Systems\r\n% One of the most obvious uses for subclassing in MATLAB is a situation\r\n% requiring a model of a real physical system that has already been\r\n% classified.  In such a situation, it might make sense to build a software\r\n% model that closely resembles the real physical classification system. For\r\n% example, one could create objects based on the Standard Model of particle\r\n% physics <http:\/\/en.wikipedia.org\/wiki\/Standard_Model [1]>.  In this way,\r\n% the classification system already exists and can simply be represented in\r\n% software.  There is still design work to be done in how best to represent\r\n% a physical system in software for a specific purpose, but all the classes\r\n% can be built at roughly the same time by the same person or team and thus\r\n% avoid the pitfalls of reusing an existing class later on after its\r\n% details have been forgotten. Here is what a superclass might look like\r\n% for elementary particles in the Standard Model:\r\ntype ElemParticle\r\n%% \r\n% We can then create subclasses for fermions and bosons:\r\ntype Fermion\r\ntype Boson\r\n%%\r\n% We can divide the Fermions into Leptons and Quarks:\r\ntype Lepton\r\ntype Quark\r\n%%\r\n% In the above example, the superclasses and subclasses were designed as a\r\n% single collection of classes so there is no need for superclasses to\r\n% anticipate the needs of unknown future subclasses.  Any future evolution\r\n% of the superclasses needs to consider the whole system, but it is a\r\n% bounded list of classes.\r\n%% Systems of Abstract Data Structures\r\n% Even if one is not modeling a physical system with an existing\r\n% classification model that makes sense in software, there are still other\r\n% examples where a system of classes can be designed at roughly the same\r\n% time to fulfill some purpose such as managing a variety of data formats\r\n% or anaysis techniques.  For example, we might have a need to visualize\r\n% some data as points.  We might know that we have two kinds of data sets:\r\n% one that is two-dimensional and one that is three-dimensional.  We design\r\n% a class that handles 2-D data and a sub-class that adds support for a\r\n% third dimension.  Here is what the 2-D class looks like:\r\ntype PointList\r\n%%\r\n% Because we know that we want to support 3-D data, we design our plotting\r\n% routine to be able to handle 2-D or 3-D data.  This is an advantage of\r\n% knowing about all the subclasses in the beginning.  Then when we write\r\n% the 3-D subclass:\r\ntype PointList3D\r\n%%\r\n% it is very easy to support 3-D plots without rewriting the whole show\r\n% method.  Here we produce a 3-D point cloud for the 3rd harmonic of the\r\n% L-shaped membrane:\r\nL = membrane(3);\r\n[X, Y] = meshgrid(1:length(L), 1:length(L));\r\npts = PointList3D;\r\npts.Z = L(:);\r\npts.X = X(:);\r\npts.Y = Y(:);\r\nshow(pts)\r\n%% Mixins \r\n% Another good reason to use subclassing is when a superclass is designed\r\n% specifically for reuse.  A common design pattern\r\n% <http:\/\/en.wikipedia.org\/wiki\/Design_pattern_(computer_science) [2]> is\r\n% called the mixin pattern <http:\/\/en.wikipedia.org\/wiki\/Mixin [3]>.  In\r\n% this pattern a class is often used to implement one specialized piece of\r\n% functionality.  This class represents all objects that have this common\r\n% functionality even though such classes may do other things very\r\n% differently.  A mixin class should expect nothing of a subclass except\r\n% that it uses the mixin functionality.  A common example of a mixin class\r\n% in MATLAB is the class called\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.customdisplay-class.html\r\n% |matlab.mixin.CustomDisplay|> which is used to customize the MATLAB\r\n% default object display while retaining appropriate consistency with other\r\n% objects.  Here is an example of this mixin being used on our\r\n% |ElemParticle| superclass. To separate this version from the previous\r\n% example, I've put the new version of the classes in a package called\r\n% |particle|.\r\ntype +particle\/ElemParticle\r\n%%\r\n% Note that whenever functionality is designed for a superclass such as\r\n% this, it is important to implement the functionality for the whole class\r\n% of objects including all instances of subclasses.  Thus, the display\r\n% should not just show what is common to |ElemParticle|, but should provide\r\n% for specialization in subclasses.  In this case, we add one method that\r\n% can be specialized by subclasses to provide lists of intrinsic\r\n% properties. Since we know about all the subclasses, we don't need to\r\n% worry about what kinds of property groups a future subclass might need.\r\n% We can see why it is important for superclasses to be designed with the\r\n% knowledge that subclasses will be created and why it is very helpful if\r\n% the subclasses are already known during this design.  In this case, we\r\n% know the family of subclasses of |ElemParticle| and thus we know that\r\n% they will sometimes need to add new properties, but not whole new groups\r\n% of properties.  We choose the right amount of generality in the\r\n% superclass so that each subclass can specialize display with minimal\r\n% effort.  In fact |Quark| is the only particle that needs additional code\r\n% as shown here:\r\ntype +particle\/Quark\r\n\r\n%%\r\n% We can now create and display an electron and a top quark:\r\ne = particle.Lepton(-1, 5.11e-4)\r\n%%\r\nt = particle.Quark(2\/3, 173.07, 'red')\r\n%% Other Patterns\r\n% Other common patterns where classes are designed for unbounded\r\n% subclassing include interfaces\r\n% <http:\/\/en.wikipedia.org\/wiki\/Interface_(computer_science) [4]> and\r\n% frameworks <http:\/\/en.wikipedia.org\/wiki\/Framework_(computer_science)\r\n% [5]>.  Interface classes define how two pieces of code can interact with\r\n% each other without actually defining how those interactions are\r\n% accomplished.  Because MATLAB is a dynamically typed language, it is\r\n% possible to write functions to an interface that isn't actually defined\r\n% as a class.  For example many functions in MATLAB can work with any\r\n% object that implements the\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/size.html |size|>,\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/subsref.html |subsref|>, and\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/subsasgn.html |subsasgn|>\r\n% functions to perform reshaping operations on arrays.  In some cases, it\r\n% may be useful to define interfaces explicitly so that it is easier to\r\n% determine what kinds of objects will work with a particular function and\r\n% so that it is easier to see the capabilities of a class in the explicit\r\n% interfaces it supports.\r\n%% Design Considerations\r\n% When designing a class for extension in the future, it is a good idea to\r\n% think about how subclasses might restrict evolution of the base class.\r\n% Some questions to consider are:\r\n%%\r\n%\r\n% * Is it clear that there will be no need to add any properties or methods\r\n% to the base class in the future?\r\n% * Is it clear that only internal implementation details will need to\r\n% change over time and not the fundamental meaning and behavior of the\r\n% class?\r\n%%\r\n% When designing methods in the base class, it is important to consider how\r\n% subclasses will reuse and as necessary adapt these methods while\r\n% maintaining the principle that subclass instances can be substituted for\r\n% base class instances\r\n% <http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle [6]>.  Some\r\n% questions to ask are:\r\n%%\r\n%\r\n% * What methods might need to be specialized?\r\n% * How can base class methods be best organized to allow subclasses to\r\n% reuse as much base class implementation as possible?\r\n% * Are there ways to better ensure that subclasses still behave\r\n% consistently with the intended behavior of the class?\r\n%%\r\n% Once a class has been presented as a base class, its fundamental\r\n% definition should not change or else subclasses could become invalid or\r\n% produce erroneous results.  The new or changed behaviors and capabilities\r\n% may not be appropriate for all subclasses.  The subclass authors could\r\n% not possibly anticipate changes to the superclass when the subclasses\r\n% were created.  This is one of the reasons for adhering to the open\/closed\r\n% design principle <http:\/\/en.wikipedia.org\/wiki\/Open\/closed_principle\r\n% [7]>.\r\n%% Preventing Unexpected Subclassing\r\n% Given the importance of considering how a class will be extended by\r\n% subclasses, MATLAB provides ways to signal that a class wasn't designed\r\n% for subclassing.  Classes with the Sealed attribute set can't be used as\r\n% superclasses.  If an entire class hierarchy was designed together but not\r\n% intended for extension with additional subclasses, then it can be sealed\r\n% using the Sealed attribute on the leaf classes and the AllowedSubclasses\r\n% attribute on the superclasses.  MathWorks will at times seal classes or\r\n% class hierarchies of widely used classes to indicate that these classes\r\n% have not been designed to support subclasses.\r\n% \r\n% These are some thoughts on subclassing in MATLAB, but I'd like to hear\r\n% your thoughts as well.  Have you used any of the mixin MATLAB classes\r\n% like\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.customdisplay-class.html\r\n% |matlab.mixin.CustomDisplay|> or\r\n% <https:\/\/www.mathworks.com\/help\/matlab\/ref\/matlab.mixin.heterogeneous-class.html\r\n% |matlab.mixin.Heterogeneous|>?  Do you have suggestions for mixin classes\r\n% that you would like to see in MATLAB? You can post ideas and comments\r\n% <https:\/\/blogs.mathworks.com\/loren\/?p=XXX#respond here>.\r\n%\r\n%% References\r\n%\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Standard_Model>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Design_pattern_(computer_science)>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Mixin>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Interface_(computer_science)>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Framework_(computer_science)>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Liskov_substitution_principle>\r\n% # <http:\/\/en.wikipedia.org\/wiki\/Open\/closed_principle>\r\n\r\n\r\n##### SOURCE END ##### 0a1da298a1364295b8588f939334a2f8\r\n-->","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/loren\/2014\/subclassblog_01.png\" onError=\"this.style.display ='none';\" \/><\/div><!--introduction--><p>I'm pleased to have Dave Foti back for a discussion of subclassing and class hierarchies in MATLAB.  Dave manages the group responsible for object-oriented programming features in MATLAB.... <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/loren\/2014\/12\/17\/subclasses-in-matlab\/\">read more >><\/a><\/p>","protected":false},"author":39,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[44],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1073"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/users\/39"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/comments?post=1073"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1073\/revisions"}],"predecessor-version":[{"id":1966,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/posts\/1073\/revisions\/1966"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/media?parent=1073"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/categories?post=1073"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/loren\/wp-json\/wp\/v2\/tags?post=1073"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}