2

I'm looking for a MATLAB solution in which a nested subclass can access the properties of another nested subclass.

In the following example the superclass has two properties which each are initialised as two different subclasses:

classdef superclass

  properties
    prop1
    prop2
  end

  methods

    function obj = superclass()
       obj.prop1 = subclass1;
       obj.prop2 = subclass2;
    end

  end
end

The first subclass has the property a:

 classdef subclass1

    properties
      a
    end

 end

The second subclass has the property b and a method calcSomething which uses the property a of subclass 1:

 classdef subclass2

    properties
      b
    end

    methods
      function result = calcSomething(obj)
        result = obj.b * superclass.prop1.a;
      end
    end

 end

How can I express superclass.prop1.a to correctly fetch this property from within subclass2?

Thank you! :)

PS I'm not sure if my usage of the words superclass and subclass is entirely correct, since I didn't state

subclass < superclass

Maybe the concept of Mother and Children would be more convenient..?!

Johannes
  • 135
  • 5
  • 1
    `prop1` has no knowlege of `superclass` nor the object of that class that contains it. You can explicitly give it this knowledge, but that would be weird. It would be more logical to make this method be part of `superclass`, which is the only class that has knowledge of both properties. – Cris Luengo Oct 07 '18 at 18:28
  • Thank you @CrisLuengo for your quick answer! And yeah, you're probably right. The `superclass` has knowledge of both properties, and therefore the method `calcSomething` should be located inside superclass... – Johannes Oct 07 '18 at 18:49

1 Answers1

1

Soo, following the main structure of superclass (which is not going to be altered) the method calcSomething will now be located inside superclass:

classdef superclass
   properties
      prop1 = subclass1
      prop2 = subclass2
   end

   methods
      function result = calcSomething(obj)
         result = obj.prop1.a * obj.prop2.b;
      end
   end
end
Johannes
  • 135
  • 5