How to write a subclass that `copies' an instance of the superclass?
4 次查看(过去 30 天)
显示 更早的评论
Basic Question: Can I make a copy of an instance of a class, but with a different version of one of the class's methods?
Details: I have a class called Domain2d which has a method threePointQuadrature. I want to rewrite the threePointQuadrature method and run tests to compare the new method versus the old method. The idea I have is to make Domain2d_exp < Domain2d which is the same in every way as Domain2d, except I will write an experimental version of the threePointQuadrature method in Domain2d_exp.
My understanding is that subclasses inherit all methods from the superclass, but will run the subclass version of a method if the subclass has a method with the same name as one of the superclass methods. So, if I have dom (an instance of Domain2d) and dom_exp (an instance of Domain2d_exp) then when I call dom.threePointQuadrature, the original version of the function will be run, and when I call dom_exp.threePointQuadrature, the the experimental version of threePointQuadrature will be run.
Now, since Domain2d_exp < Domain2d I would normally write the constructor for Domain2d_exp to take the same parameters as Domain2d, and then just call the superclass constructor for Domain2d from within the constructor for Domain2d_exp. However, the issue in this case is that once a Domain2d object has been instantiated, it must be configured, which requires several other lines of code, and is somewhat costly in terms of time. So what I'd rather do is instantiate and configure dom, and instance of Domain2d, and then pass dom to the constructor for Domain2d_exp, which will retain all the properties and methods of dom, but with the experimental threePointQuadrature method.
Is this possible? Or, is there a better way to acheive the same end result?
0 个评论
回答(1 个)
Umar
2024-8-10
Hi @ Tyler Fara,
This is an interesting question, To address your query regarding, “Can I make a copy of an instance of a class, but with a different version of one of the class's methods?”
Try creating a subclass Domain2d_exp that inherits from Domain2d and override the threePointQuadrature method in the subclass. This way, instances of Domain2d_exp will use the experimental version of the method while retaining other properties and methods from Domain2d. Pass the Domain2d instance to the constructor of Domain2d_exp to retain the properties and configuration of an existing Domain2d instance and to use it in Domain2d_exp. After creating the experimental subclass and initializing it with an existing Domain2d instance, you can run tests to compare the original method with the experimental one. Please let me know if you have any further questions.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Subclass Applications 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!