MATLAB Object-Oriented Programming

(Joyce) #1

Changes to Class Constructors


Class constructor methods have two major differences. Class constructors:


  • Do not use the class function.

  • Must call the superclass constructor only if you want to pass arguments to its
    constructor. Otherwise, no call to the superclass constructor is necessary.


Example of Old and New Syntax

Compare the following two Stock constructor methods. The Stock class is a subclass of
the Asset class, which requires arguments passed to its constructor.

Constructor Function Before Version 7.6

function s = Stock(description,num_shares,share_price)
s.NumShares = num_shares;
s.SharePrice = share_price;
% Construct Asset object
a = Asset(description,'stock',share_price*num_shares);
% Use the class function to define the stock object
s = class(s,'Stock',a);

Write the same Stock class constructor as shown here. Define the inheritance on the
classdef line and define the constructor within a methods block.

Constructor Function for Version 7.6

classdef Stock < Asset
...
methods

function s = Stock(description,num_shares,share_price)
% Call superclass constructor to pass arguments
s = s@Asset(description,'stock',share_price*num_shares);
s.NumShares = num_shares;
s.SharePrice = share_price;
end % End of function

end % End of methods block
end % End of classdef block

5 Class Definition—Syntax Reference

Free download pdf