What is the correct way to update super class properties?

조회 수: 7 (최근 30일)
Grzegorz Lippe
Grzegorz Lippe 2022년 3월 8일
답변: Prince Kumar 2022년 3월 31일
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

답변 (1개)

Prince Kumar
Prince Kumar 2022년 3월 31일
Hi,
Please refer to the following documentation
It has been clearly explained here.
Hope this helps!

카테고리

Help CenterFile Exchange에서 Construct and Work with Object Arrays에 대해 자세히 알아보기

제품


릴리스

R2019b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by