Default property values can help you implement version compatibility for saved objects. For example, suppose that you add a property to version 2 of your class. Having a default value enables MATLAB® to assign a value to the new property when loading a version 1 object.
Similarly, suppose version 2 of your class removes a property. If a version 2 object is saved and loaded into version 1, your loadobj
method can use the default value from version 1.
The EmployeeInfo
class shows how to use property default values as a way to enhance compatibility among versions. Version 1 of the EmployeeInfo
class defines three properties — Name
, JobTitle
, and Department
.
classdef EmployeeInfo properties Name JobTitle Department end end
Version 2 of the EmployeeInfo
class adds a property, Country
, for the country name of the employee location. The Country
property has a default value of 'USA'
.
classdef EmployeeInfo properties Name JobTitle Department Country = 'USA' end end
The character array, 'USA'
, is a good default value because:
MATLAB assigns an empty double []
to properties that do not have default values defined by the class. Empty double is not a valid value for the Country
property.
In version 1, all employees were in the USA. Therefore, any version 1 object loaded into version 2 receives a valid value for the Country
property.