MATLAB: Setter method does not work on inherited class

classinheritanceoopsetter

How can I make setter function works on a child class?
classdef Foo < matlab.mixin.Heterogeneous
properties
foo = 5;
end
methods
function setFoo(obj, foo)
obj.foo = foo;
end
end
end
classdef BabyFoo < Foo
methods
function obj = BabyFoo()
obj = obj@Foo();
end
end
end
>> test = BabyFoo();
>> test.foo; % 5
>> test.setFoo(10);
>> test.foo; % 5 (Why it's not 10 ?!)

Best Answer

You're using handle syntax to set the property of your class, yet your class is a value class. Either change your setFoo to:
function obj = setFoo(obj, foo)
obj.foo = foo;
end
and call it with:
test = test.setFoo(10);
or derive from handle:
classdef Foo < matlab.mixin.Heterogeneous & handle
Also, you can create setter and getter for the class properties, using this syntax
function set.foo(obj, value) %for handle class
obj.foo = value;
end
function obj = set.foo(obj, value) % for value class
obj.foo = value;
end
which you call simply with:
obj.foo = 10; %for value and handle class.