What is the correct way to update super class properties?
4 views (last 30 days)
Show older comments
I have a class which serves as a data class for objects with the same pattern. In my example I will use a class Surface:
% Surface.m
classdef Surface
properties
area
circumference
end
methods
function obj = Surface(area, circumference)
obj.area = area ;
obj.circumference = circumference ;
end
end
end
Now there are different methods to construct a so called Surface class and since I cannot define multiple constructors for Surface in Matlab I create subclasses which are all of the type Surface, in my example a class Circle.
% Circle.m
classdef Circle < Surface
properties
r
end
methods
function obj = Circle(r)
obj@Surface(0, 0)
obj.r = r ;
obj.area = pi * r^2 ;
obj.circumference = 2 * pi * r ;
end
end
end
Now I want a object of type circle to update its superclass properties when its properties are changed. How can I solve this? If the property would be in the class itself I would use a dependent property, but what is the correct pattern, if the property is in a superclass?
% test_classes.m
function tests = test_classes
tests = functiontests(localfunctions);
end
function test_surface(~)
area = 2 ;
circumference = 3 ;
s = Surface(area, circumference) ;
assert(s.area == area) ;
assert(s.circumference == circumference) ;
end
function test_circle(~)
r = 2 ;
area = pi * r^2 ;
circumference = 2 * pi * r ;
c = Circle(r) ;
assert(c.area == area) ;
assert(c.circumference == circumference) ;
end
function test_cicle_change_property(~)
% Change circle property THIS WILL FAIL
c = Circle(2) ; % Create Class
c.r = 6 ; % changed property
r = 6 ; % update test values.
area = pi * r^2 ; % update test values.
circumference = 2 * pi * r ; % update test values.
assert(c.area == area) ; % <-- how do I fix this?
assert(c.circumference == circumference) ;
end
0 Comments
Answers (1)
Prince Kumar
on 31 Mar 2022
Hi,
Please refer to the following documentation
It has been clearly explained here.
Hope this helps!
0 Comments
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!