MATLAB Object-Oriented Programming

(Joyce) #1

Heterogeneous Array Constructors


In this section...
“Building Arrays in Superclass Constructors” on page 10-34
“When Errors Can Occur” on page 10-34
“Initialize Array in Superclass Constructor” on page 10-35
“Sample Implementation” on page 10-36
“Potential Error” on page 10-38

Building Arrays in Superclass Constructors


When a subclass in a heterogeneous class hierarchy calls its superclass to construct an
array of objects, you must ensure that the superclass constructor does not return a
heterogeneous array to the subclass. The following programming patterns show how to
avoid the errors caused by returning the wrong class to the subclass constructor.

When Errors Can Occur


Constructors must return objects that are the same class as the defining class. When
working with objects from a heterogeneous class hierarchy, the class of an object array
can change as you add array elements of different classes. As a result, heterogeneous
superclass constructors can change the class of object arrays when the class design
requires all the following techniques:


  • Building object arrays in subclass constructors

  • Calling superclass constructors from subclass constructors to pass arguments

  • Creating object arrays in the superclass constructor


In addition, either of the following is true:


  • The root superclass is not abstract and does not implement a
    getDefaultScalarElement method.

  • The root superclass implements a getDefaultScalarElement method that returns
    an object that is not the same class as the subclass.


When assigning to object arrays, MATLAB uses the default object to fill in unassigned
array elements. In a heterogeneous hierarchy, the default object can be the superclass

10 Object Arrays

Free download pdf