Comparing Handle and Value Classes

Why Select Handle or Value

MATLAB support two kinds of classes — handle classes and value classes. The kind of class you use depends on the desired behavior of the class instances and what features you want to use.

Use a handle class when you want to create a reference to the data contained in an object of the class, and do not want copies of the object to make copies of the object data. For example, use a handle class to implement an object that contains information for a phone book entry. Multiple application programs can access a particular phone book entry, but there can be only one set of underlying data.

The reference behavior of handles enables these classes to support features like events, listeners, and dynamic properties.

Use value classes to represent entities that do not need to be unique, like numeric values. For example, use a value class to implement a polynomial data type. You can copy a polynomial object and then modify its coefficients to make a different polynomial without affecting the original polynomial.

Which Kind of Class to Use describes how to select the kind of class to use for your application.

Passing Objects to Functions compares handle and value object behavior when used as arguments to functions.

Behavior of MATLAB Built-In Classes

If you create an object of the class int32 and make a copy of this object, the result is two independent objects having no data shared between them. The following code example creates an object of class int32 and assigns it to variable a, and then copies it to b. When you raise a to the fourth power and assign the value again to the variable a, MATLAB creates an object with the new data and assigns it to the variable a, overwriting the previous assignment. The value of b does not change.

a = int32(7);
b = a;
a = a^4;

MATLAB copies the value of a to b, which results in two independent versions of the original object. This behavior is typical of MATLAB numeric classes.

Handle Graphics classes return a handle to the object created. A handle is a variable that references an instance of a class. If you copy the handle, you have another variable that refers to the same object. There is still only one version of the object data. For example, if you create a Handle Graphics line object and copy its handle to another variable, you can set the properties of the same line using either copy of the handle.

x = 1:10; y = sin(x);
h1 = line(x,y);
h2 = h1;

>>set(h2,'Color','red') % line is red
>>set(h1,'Color','green') % line is green
??? Error using ==> set
Invalid handle object.

[help]Note also, if you delete one handle, all copies are now invalid because you have deleted the single object that all copies point to.[/help]

Behavior of User-Defined Classes

Value class instances behave like built-in numeric classes and handle class instances behave like Handle Graphics objects, as illustrated in Behavior of MATLAB Built-In Classes.

Value Classes

MATLAB associates objects of value classes with the variables to which you assign them. When you copy a value object, MATLAB also copies the data contained by the object. The new object is independent of changes to the original object. Instances behave like standard MATLAB numeric and struct classes. Each property behaves essentially like a MATLAB array See Memory Allocation for Arrays for more information.

Value Class Behavior

Use value classes when assigning an object to a variable and passing an object to a function must make a copy of the function. Value objects are always associated with one workspace or temporary variable and go out of scope when that variable goes out of scope or is cleared. There are no references to value objects, only copies which are themselves objects.

For example, suppose you define a polynomial class whose Coefficients property stores the coefficients of the polynomial. Note how copies of these value-class objects are independent of each other:

p = polynomial([1 0 -2 -5]);
p2 = p;
p.Coefficients = [2 3 -1 -2 -3];
ans = 
   1 0 -2 -5

Creating a Value Class

All classes that are not subclasses of the handle class are value classes. Therefore, the following classdef creates a value class named myValueClass:

classdef myValueClass 

Handle Classes

Objects of handle classes use a handle to reference objects of the class. A handle is a variable that identifies an instance of a class. When you copy a handle object, MATLAB copies the handle, but not the data stored in the object properties. The copy refers to the same data as the original handle. If you change a property value on the original object, the copied object reflects the same change.

All handle classes are subclasses of the abstract handle class. In addition to providing handle copy semantics, deriving from the handle class enables your class to:

  • Inherit a number of useful methods (Handle Class Methods)
  • Define events and listeners (Defining Events and Listeners — Syntax and Techniques)
  • Define dynamic properties (Dynamic Properties — Adding Properties to an Instance)
  • Implement Handle Graphics type set and get methods (Implementing a Set/Get Interface for Properties)

Creating a Handle Class

Subclass the handle class explicitly to create a handle class:

classdef myClass < handle

[important]See The Handle Superclass for more information on the handle class and its methods.[/important]

Subclasses of Handle Classes

If you subclass a class that is itself a subclass of the handle class, your subclass is also a handle class. You do not need to specify the handle superclass explicitly in your class definition. For example, the employee class is a subclass of the handle class:

classdef employee < handle 

Create a subclass of the employee class for engineer employees, which is also a handle class. You do not need to specify handle as a superclass in the classdef:

classdef engineer < employee 

Handle Class Behavior

A handle is an object that references its data indirectly. When constructing a handle, the MATLAB runtime creates an object with storage for property values and the constructor function returns a handle to this object. When you assign the handle to a variable or when you pass the handle to a function, MATLAB copies the handle, but not the underlying data.

For example, suppose you have defined a handle class that stores data about company employees, such as the department in which they work:

classdef employee < handle 
      Name = ''
      Department = '';
      function e = employee(name,dept)
         e.Name = name;
         e.Department = dept;
      end % employee
      function transfer(obj,newDepartment)
         obj.Department = newDepartment;
      end % transfer

The transfer method in the previous code changes the employee's department (the Department property of an employee object). In the following statements, e2 is a copy of the handle object e. Notice that when you change the Department property of object e, the property value also changes in object e2.

e = employee('Fred Smith','QE');
e2 = e; % Copy handle object
ans =

The variable e2 is an alias for e and refers to the same property data storage as e.

Initializing Properties to Handle Objects

See How to Initialize Property Values for information on the differences between initializing properties to default values in the properties block and initializing properties from within the constructor. Also, see Arrays of Handle Objects for related information on working with handle classes.

employee as a Value Class

If the employee class was a value class, then the transfer method would modify only its local copy of the employee object. In value classes, methods like transfer that modify the object must return a modified object to copy over the existing object variable:

function obj = transfer(obj,newDepartment)
   obj.Department = newDepartment;

When you call transfer, assign the output argument to create the modified object.

e = transfer(e,'Engineering');

In a value class, the transfer method does not affect the variable e2, which is a different employee object. In this example, having two independent copies of objects representing the same employee is not a good design. Hence, implement the employee class as a handle class.

Deleting Handles

You can destroy handle objects before they become unreachable by explicitly calling the delete function. Deleting the handle of a handle class object makes all handles invalid. For example:

??? Invalid or deleted object.

Calling the delete function on a handle object invokes the destructor function or functions for that object. See Handle Class Delete Methods for more information.

You may also like...