How to synchronise inherited properties of class
1 view (last 30 days)
Show older comments
I have a superclass TubeClass with a number of properties, one of which is outsideDiameter. From this superclass, I derive two subclasses, StraightTubeClass and BentTubeClass. Both of these classes inherit the property outsideDiameter. So far so good...
I would now like to create a third class, UTubeClass, which again inherets from TubeClass. Now, UTubeClass comprises two straight legs of tube and a 180° bend. It also inherits the outsideDiameter property. So now I have a construction something like
MyUTube = UTubeClass; % Make new U-tube object
MyUTube.outsideDiameter = 100
MyUTube.someOtherProperties = 'foo'
MyUTube.straightLeg.outsideDiameter = 100
MyUTube.bend.outsideDiameter = 100
Ideally the outsideDiameter property would be the same in all places. I can figure out how to create a set method for UTubeClass such that when I set the property of outside diameter it is synchronised across all three usages, eg
MyUTube = UTubeClass;
MyUTube.outsideDiameter = 500;
% results in...
MyUTube.outsideDiameter = 500
MyUTube.straightLeg.outsideDiameter = 500
MyUTube.bend.outsideDiameter = 500
However, it is still possible to break this and independently set the value of the straight leg or bend outside diameter, eg
MyUTube = UTubeClass;
MyUTube.outsideDiameter = 500;
% results in...
MyUTube.outsideDiameter = 500
MyUTube.straightLeg.outsideDiameter = 500
MyUTube.bend.outsideDiameter = 500
% however...
MyUTube.straightLeg.outsideDiameter = 1000; % makes no sense, because now the OD is out of synch with the other values
So, is there a way to prevent this behavour, or should I be approaching the problem differently.
0 Comments
Accepted Answer
Jeff Miller
on 15 Oct 2019
I would say your UTubeClass should not descend from TubeClass. It's not the case that UTube "is a" Tube, but rather than UTube "has a" tube (or, really, it has two of them--one bent and one straight).
Another way to say it is that the UTube does not have its own independent diameter, separately from the diameters of its component straight and bent tubes, so there shouldn't be a separate property for UTube.outsideDiameter.
2 Comments
Steven Lord
on 15 Oct 2019
Indeed. The way I'd probably implement this is by giving UTubeClass properties that contain (as you said, has-a versus is-a) a StraightTube and a BentTube. The property set methods for those properties would validate that they have compatible outsideDiameter values.
More Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!