MATLAB CLASSES getter and setters

matlab, matlab-class, oop

Solution

Implementation

Since your class is currently a subclass of the default Value class, your setters need to return the modified object:

function obj = set.name(obj,name)
end
function obj = set.age(obj,age)
end

From the documention: "If you pass [a value class] to a function, the function must return the modified object." And in particular: "In value classes, methods ... that modify the object must return a modified object to copy over the existing object variable".

Handle classes (`classdef Person < handle`) do not need to return the modified object (like returning `void`):

function [] = set.name(obj,name)
end
function [] = set.age(obj,age)
end

Value vs. Handle

Going a bit deeper, the difference between a Value class and a Handle class lies mostly in assignment:

- Assigning a Value class instance to a variable creates a copy of that class.

- Assigning a Handle class instance to a variable create a reference (alias) to that instance.

The Mathworks has a good rundown on this topic. To paraphrase their illustration, the behavior of a Value class is

% p  is an instance of Polynomial
p = Polynomial(); 
% p2 is also an instance of Polynomial with p's state at assignment
p2 = p;

and of a Handle class is

% db is an instance of Database
db = Database();
% db2 is a reference to the db instance
db2 = db;

Problem

I come from a Java background. I am having issues with classes in Matlab particularly getters and setters. getting a message saying conflict between handle and value class I'm a little lost with what to do so any help for lack of a better word will be helpful. ``` classdef Person properties(Access = private) name; age; end methods % class constructor function obj = Person(age,name) obj.age = age; obj.name = name; end %getters function name = get.name(obj) end function age = get.age(obj) end %setters function value = set.name(obj,name) end function value = set.age(obj,age) end end ``` end

Original source