Heritage instance information to another instance
2 次查看(过去 30 天)
显示 更早的评论
I have a class named "OriginalTirePattern". it includes various tire deisgn parameters. and there is another class names "DeformedTirePattern". it is a subclass of "OriginalTirePattern" class. Suppose there is one instance of "OriginalTirePattern"(Let's call it Instance1). Here, I want to design a new deformed tire pattern based on it and save deformed tire pattern as instance of "DeformedTirePattern" class(Instance2) which includes original tire pattern information as well as deformation information.
So my question is that
"Is there a good way to pass information of Instance1 to Instance2?(in case of class of Instance2 is a subclass of Instance1)"
0 个评论
回答(1 个)
Jaynik
2023-12-14
Hi,
I understand that you want to pass the property information from parent class to child class.
In object-oriented programming, an instance of a subclass does not automatically have access to the specific data of an instance of its superclass unless it is explicitly passed or shared. Inheritance allows the subclass to inherit the structure (properties and methods) of the superclass, not the data of a particular instance.
Hence to automatically pass the information, you will need to pass the object as a parameter to the child class instance. You can look at the following code for reference:
classdef OriginalTirePattern
properties
tireType
tireSize
end
methods
function obj = OriginalTirePattern(type, size)
obj.tireType = type;
obj.tireSize = size;
end
end
end
Here, the class "OriginalTirePattern" has two properties, "tireType" and "tireSize".
classdef DeformedTirePattern < OriginalTirePattern
properties
deformedTireProperty
end
methods
function obj = DeformedTirePattern(originalInstance, deformedTireProperty)
obj = obj@OriginalTirePattern(originalInstance.tireType, originalInstance.tireSize);
obj.deformedTireProperty = deformedTireProperty;
end
end
end
Here, the class "DeformedTireProperty" uses the object of "OriginalTirePattern" and its own property called "deformedTireProperty" in the constructor initialization.
You can then call the class as follows to have the values consistent in both classes. The properties of "OriginalTirePattern" can also be used due to inheritence.
instance1 = OriginalTirePattern("type1", "size1");
instance2 = DeformedTirePattern(instance1, deformationInfo);
disp(instance2.tireType);
You can refer to the following documentation for more information: https://www.mathworks.com/help/matlab/matlab_oop/modifying-superclass-methods-and-properties.html
Hope this helps!
Regards,
Jaynik
0 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!