Advantages of a Class vs. a Structure
Treat the TensileData object (td in the previous statements) much as you would any
MATLAB structure. However, defining a specialized data structure as a class has
advantages over using a general-purpose data structure, like a MATLAB struct:
- Users cannot accidentally misspell a field name without getting an error. For example,
typing the following:
td.Modulis = ...
would simply add a field to a structure. However, it returns an error when td is an
instance of the TensileData class.
- A class is easy to reuse. Once you have defined the class, you can easily extend it with
subclasses that add new properties. - A class is easy to identify. A class has a name so that you can identify objects with the
whos and class functions and the Workspace browser. The class name makes it easy
to refer to records with a meaningful name. - A class can validate individual field values when assigned, including class or value.
- A class can restrict access to fields, for example, allowing a particular field to be read,
but not changed.
Restrict Properties to Specific Values
Restrict properties to specific values by defining a property set access method. MATLAB
calls the set access method whenever setting a value for a property.
Material Property Set Function
The Material property set method restricts the assignment of the property to one of the
following strings: aluminum, stainless steel, or carbon steel.
Add this function definition to the methods block.
classdef TensileData
properties
Material
SampleNumber
Stress
Strain
Modulus
Representing Structured Data with Classes