What is the correct way to update super class properties?

5 ビュー (過去 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 Center および File ExchangeConstruct 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