How can I avoid infinite loop when I define my superclass?
9 次查看(过去 30 天)
显示 更早的评论
I wrote a superclass which defines an object filling up some of the properties with user given inputs. The value of the rest of the properties should be dependent on one of the given inputs. To be more concrete:
The superclass should have 3 properties: DataSet Type Method Parameter
The constructor should receive 3 inputs, one of them will be used as DataSet (vector of doubles), the other one is a single character, eithe 'A' or 'B', defining the type of the data set, and the EstimationMethod can be 'X' or 'Y', which specifies a method how I want to compute the parameter for a dataset.
The important thing to note is that the two Estimation methods should be different for A and B typed datasets. My idea was to define two subclasses, one for Type=A and one for Type=B. The subclasses would inherit the dataSet from the superclass as well as the EstimationMethod. In these subclasses I would like to implement X and Y EstimationMethods corresponding to Type A and Type B.
What I expect to see: In my script, when I define an onject, let's say, Object1=Superclass(DataSet1,'A','Y'), the constructor should call the Type A subclass, use the Y method implemented in that subclass to compute the parameter value, and add it as a value of the superclass object.
In my script, I don't want to call sublasses directly, but I want them to be called by the superclass. I am not sure this concept is a working one, because when I implemented it, it resulted an infinite loop. The superclass constructor called the subclass which tried to inherit properties from superclass, whi called subclass again, etc..
Could you please let me know if what I want to do is conceptually good, and if yes, help me with a sketch of the implementation?
Thank you in advance
0 个评论
采纳的回答
Steven Lord
2017-6-12
Use the factory pattern. Create a separate function (don't attempt to reuse the constructor for any of the subclasses) that accepts the name of the subclass to create or a function handle to the constructor and have that function call the appropriate constructor.
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Construct and Work with Object Arrays 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!