lhcgeneva
lhcgeneva

Reputation: 1981

Modifying subclass properties with superclass function in Matlab

My subclass has the same properties as my superclass. This looks like the following

classdef superclass < handle
    properties
      a
      b
      c
    methods
      function sup = superclass(...)
          sup.create(...)
      end

classdef subclass < superclass
    properties
      a1
      b1
      c1
    methods
      function sub = subclass(...)

Now I would like the constructor of subclass to first initialise the superclass properties

    sub@superclass()

and then (this is where I am stuck) the subclass constructor to secondly initialise all the values a1, b1, c1. Since the procedure which initialises the properties does not change between sup and sub, I would like to reuse it like this:

    function sub = subclass(args1, args2)
       sub@superclass(args1)
       sub.create(args2)

How can I reach this, without writing a new 'create' function for the subclass?

Upvotes: 3

Views: 533

Answers (1)

Amro
Amro

Reputation: 124573

One possibility is to refactor the create method to return three values (instead of hard-coding the properties), then you can call it in both the superclass and the sublcass as:

[sup.a,sup.b,sup.c] = sup.create(...);

and

[sub.a1,sub.b1,sub.c1] = sub.create(args2);

where

classdef superclass < handle
    methods (Access = protected)
        function [x,y,z] = create(obj, args)
            x = ..; y = ...; z = ...;
        end
    end
end

Alternatively, you could perhaps use dynamic field names to abstract that part:

propname = 'a';
obj.(propname) = 0;

and have the create method receive a cell array of strings containing the property names to fill.

Upvotes: 2

Related Questions