MATLAB Object-Oriented Programming

(Joyce) #1

Comparison of Handle and Value Classes


In this section...
“Basic Difference” on page 7-2
“Behavior of MATLAB Built-In Classes” on page 7-3
“User-Defined Value Classes” on page 7-4
“User-Defined Handle Classes” on page 7-5
“Determining Equality of Objects” on page 7-8
“Functionality Supported by Handle Classes” on page 7-10

Basic Difference


A value class constructor returns an object that is associated with the variable to which it
is assigned. If you reassign this variable, MATLAB creates an independent copy of the
original object. If you pass this variable to a function to modifying it, the function must
return the modified object as an output argument. For information on value-class
behavior, see “Avoid Unnecessary Copies of Data”.

A handle class constructor returns a handle object that is a reference to the object
created. You can assign the handle object to multiple variables or pass it to functions
without causing MATLAB to make a copy of the original object. A function that modifies a
handle object passed as an input argument does not need to return the object.

All handle classes are derived from the abstract handle class.

Create a Value Class

By default, MATLAB classes are value classes. The following definition creates a value
class named MyValueClass:

classdef MyValueClass
...
end

Create a Handle Class

To create a handle class, derive the class from the handle class.

7 Value or Handle Class — Which to Use

Free download pdf