Force super class to not call overloaded methods of the subclass
13 ビュー (過去 30 日間)
古いコメントを表示
I have a base class and subclass inheriting from it. Base class has method A. Subclass overloads that method. I want to force the base class to use (only in some places) it's own method, not the one overloaded by subclass. Is there any way to do it?
Thank you
0 件のコメント
回答 (3 件)
Matt J
2024 年 4 月 28 日
編集済み: Matt J
2024 年 4 月 28 日
In any superclass method, you can test whether the invoking object is of the base class or one of its children. Depending on the result of this test, you can clone the child's base component for the purposes of calling base methods only. The attachments give an example of this.
parent=myclass(1), child=mysubclass(1,2)
parent.callingMethod()
child.callingMethod()
child.callingMethod(scope="Parent")
1 件のコメント
Matt J
2024 年 4 月 28 日
編集済み: Matt J
2024 年 4 月 28 日
You can also have the desired calling scope set through the a property, as in the attached modifications. This would be the better design if you want all methods to make this sort of scope check.
parent=myclass(1), child=mysubclass(1,2)
parent.callingMethod()
child.callingMethod()
child.callingScope="Parent";
child.callingMethod()
Shraddha Jain
2021 年 6 月 22 日
Hi Naum,
When you create an object obj of a superclass and then use obj to call the overloaded (or any) method of the superclass, the method defined in the superclass is called and not the one of the subclass.
2 件のコメント
Steven Lord
2024 年 4 月 26 日
You can call a superclass method even if the subclass overloads or overrides that method only from within that method itself. So if the superclass and subclass both define a method foo(), inside the subclass foo() method you can call the superclass's foo() method.
You can also have the subclass's constructor call the superclass's constructor (even though they don't have the same name.)
3 件のコメント
Steven Lord
2024 年 4 月 26 日
I'm not sure I understand what you're trying to do. Can you describe in a little more detail what problem you're trying to solve (not how you're hoping to implement it; describe the why not the how), or perhaps what design pattern you're trying to implement? With that information we may be able to suggest an approach to achieve your goal (or explain if it smells a bit funny to us.)
A.B.
2024 年 4 月 28 日
編集済み: A.B.
2024 年 4 月 28 日
The superclass has method make and premake. The subclass also overloads both methods. It appears any method within the superclass which is calling make or premake, calls the overloaded methods of the subclass (and not those of superclass). This behavior messes up everything. I sincerely hope I am doing something wrong, otherwise this behavior is completely counter intuitivie for me.
参考
カテゴリ
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!