Documentation Center

  • Trial Software
  • Product Updates

A Simple Class Hierarchy

Shared and Specialized Properties

As an example of how subclasses are specializations of more general classes, consider an asset class that can be used to represent any item that has monetary value. Some examples of assets are stocks, bonds, and savings accounts. This example implements four classes — DocAsset, and the subclasses DocStock, DocBond, DocSavings.

The DocAsset class holds the data that is common to all of the specialized asset subclasses in class properties. The subclasses inherit the super class properties in addition to defining their own properties. The subclasses are all kinds of assets.

The following diagram shows the properties defined for the classes of assets.

The DocStock, DocBond, and DocSavings classes inherit properties from the DocAsset class. In this example, the DocAsset class provides storage for data common to all subclasses and shares methods with these subclasses.

Designing a Class for Financial Assets

This class provides storage and access for information common to all asset children. It is not intended to be instantiated directly, so it does not require an extensive set of methods. The class contains the following methods:

  • Constructor

  • A local setter function for one property

Displaying the Class Files

Open the DocAsset class definition file in the MATLAB Editor.Open the DocAsset class definition file in the MATLAB Editor.

To use the class, create a folder named @DocAsset and save DocAsset.m to this folder. The parent folder of @DocAsset must be on the MATLAB® path.

Summary of the DocAsset Class

The class is defined in one file, DocAsset.m, which you must place in an @ folder of the same name. The parent folder of the @DocAsset folder must be on the MATLAB path. See the addpath function for more information.

The following table summarizes the properties defined for the DocAsset class.

DocAsset Class Properties

Name

Class

Default

Description

Description

char

''

Description of asset

CurrentValue

double

0

Current value of asset

Date

char

date

Date when record is created (set by date function)

Type

char

'savings'

Type of asset (stock, bond, savings)

The following table summarizes the methods for the DocAsset class.

DocAsset Class Methods

Name

Description

DocAsset

Class constructor

disp

Displays information about this object

set.Type

Set function for Type. Property tests for correct value when property is set.

The DocAsset Constructor Method

This class has four properties that store data common to all of the asset subclasses. All except Date are passed to the constructor by a subclass constructor. Date is a private property and is set by a call to the date function.

  • Description — A character string that describes the particular asset (e.g., stock name, savings bank name, bond issuer, and so on).

  • Date — The date the object was created. This property's set access is private so that only the constructor assigns the value using the date command when creating the object.

  • Type — The type of asset (e.g., savings, bond, stock). A local set function provides error checking whenever an object is created.

  • CurrentValue — The current value of the asset.

Property Definition Block

The following code block shows how the properties are defined. Note the set function defined for the Type property. It restricts the property's values to one of three strings: bond, stock, or savings.

properties
   Description = '';
   CurrentValue = 0;
end
properties(SetAccess = private)
   Date % Set value in constructor
   Type = 'savings'; % Provide a default value
end

Constructor Method Code

The DocAsset class is not derived from another class, so you do not need to call a superclass constructor. MATLAB constructs an object when you assign values to the specified output argument (a in the following code):

function a = DocAsset(description,type,current_value)
% DocAsset constructor
   if nargin > 0
      a.Description = description;
      a.Date = date; 
      a.Type = type;
      a.CurrentValue = current_value;
   end
end % DocAsset

Set Function for Type Property

In this class design, there are only three types of assets—bonds, stocks, and savings. Therefore, the possible values for the Type property are restricted to one of three possible stings by defining a set function as follows:

	function obj = set.Type(obj,type)
   if ~(strcmpi(type,'bond') || strcmpi(type,'stock') || strcmpi(type,'savings'))
      error('Type must be either bond, stock, or savings')
   end
   obj.Type = type;
	end %Type set function

The MATLAB runtime calls this function whenever an attempt is made to set the Type property, even from within the class constructor function or by assigning an initial value. Therefore, the following statement in the class definition would produce an error:

properties
   Type = 'cash';
end

The only exception is the set.Type function itself, where the statement:

obj.Type = type;

does not result in a recursive call to set.Type.

The DocAsset Display Method

The asset disp method is designed to be called from child-class disp methods. Its purpose is to display the data it stores for the child object. The method simply formats the data for display in a way that is consistent with the formatting of the child's disp method:

function disp(a)
% Display a DocAsset object
   fprintf('Description: %s\nDate: %s\nType: %s\nCurrentValue:%9.2f\n',...
   a.Description,a.Date,a.Type,a.CurrentValue);
end % disp

The DocAsset subclass display methods can now call this method to display the data stored in the parent class. This approach isolates the subclass disp methods from changes to the DocAsset class.

Designing a Class for Stock Assets

Stocks are one type of asset. A class designed to store and manipulate information about stock holdings needs to contain the following information about the stock:

  • The number of shares

  • The price per share

In addition, the base class (DocAsset) maintains general information including a description of the particular asset, the date the record was created, the type of asset, and its current value.

Displaying the Class Files

Open the DocStock class definition file in the MATLAB Editor.Open the DocStock class definition file in the MATLAB Editor.

To use the class, create a folder named @DocStock and save DocStock.m to this folder. The parent folder of @DocStock must be on the MATLAB path.

Summary of the DocStock Class

This class is defined in one file, DocStock.m, which you must place in an @ folder of the same name. The parent folder of the @DocStock folder must be on the MATLAB path. See the addpath function for more information.

DocStock is a subclass of the DocAsset class.

The following table summarizes the properties defined for the DocStock class.

DocStock Class Properties

Name

Class

Default

Description

NumShares

double

0

Number of shares of a particular stock

SharePrice

double

0

Current value of asset

Properties Inherited from the DocAsset Class

Description

char

''

Description of asset

CurrentValue

double

0

Current value of asset

Date

char

date

Date when record is created (set by date function)

Type

char

''

Type of asset (stock, bond, savings)

The following table summarizes the methods for the DocStock class.

DocStock Class Methods

Name

Description

DocStock

Class constructor

disp

Displays information about the object

Specifying the Base Class

The < symbol specifies the DocAsset class as the base class for the DocStock class in the classdef line:

classdef DocStock < DocAsset

Property Definition Block

The following code shows how the properties are defined:

properties
   NumShares = 0;
   SharePrice = 0;
end

Using the DocStock Class

Suppose you want to create a record of a stock asset for 200 shares of a company called Xdotcom with a share price of $23.47.

Call the DocStock constructor function with the following arguments:

  • Stock name or description

  • Number of shares

  • Share price

For example, the following statement:

XdotcomStock = DocStock('Xdotcom',200,23.47);

creates a DocStock object, XdotcomStock, that contains information about a stock asset in Xdotcom Corp. The asset consists of 200 shares that have a per share value of $23.47.

The DocStock Constructor Method

The constructor first creates an instance of a DocAsset object since the DocStock class is derived from the DocAsset class (see The DocAsset Constructor Method). The constructor returns the DocStock object after setting value for its two properties:

function s = DocStock(description,num_shares,share_price)
   if nargin ~= 3 % Support no argument constructor syntax
      description = '';
      num_shares = 0;
      share_price = 0;
   end
   s = s@DocAsset(description,'stock',share_price*num_shares);
   s.NumShares = num_shares;
   s.SharePrice = share_price;
end % DocStock

The DocStock disp Method

When you issue the statement (without terminating with a semicolon):

XdotcomStock = DocStock('Xdotcom',100,25)

the MATLAB runtime looks for a method in the @DocStock folder called disp. The disp method for the DocStock class produces this output:

Description: Xdotcom 
Date: 17-Nov-1998
Type: stock
Current Value:  $2500.00
Number of shares: 100
Share price: $25.00

The following function is the DocStock disp method. When this function returns from the call to the DocAsset disp method, it uses fprintf to display the Numshares and SharePrice property values on the screen:

function disp(s)
   disp@DocAsset(s)
   fprintf('Number of shares: %g\nShare price: %3.2f\n',...
   s.NumShares,s.SharePrice);
end % disp

Designing a Class for Bond Assets

The DocBond class is similar to the DocStock class in that it is derived from the DocAsset class to represent a specific type of asset.

Displaying the Class Files

Open the DocBond class definition file in the MATLAB Editor.Open the DocBond class definition file in the MATLAB Editor.

To use the class, create a folder named @DocBond and save DocBond.m to this folder . The parent folder of @DocBond must be on the MATLAB path. See the addpath function for more information.

Summary of the DocBond Class

This class is defined in one file, DocBond.m, which you must place in an @ folder of the same name. The parent folder of the @DocBond folder must on the MATLAB path.

DocStock is a subclass of the DocAsset class.

The following table summarize the properties defined for the DocBond class

DocBond Class Properties

Name

Class

Default

Description

FaceValue

double

0

Face value of the bond

SharePrice

double

0

Current value of asset

Properties Inherited from the DocAsset Class

Description

char

''

Description of asset

CurrentValue

double

0

Current value of asset

Date

char

date

Date when record is created (set by date function)

Type

char

''

Type of asset (stock, bond, savings)

The following table summarizes the methods for the DocStock class.

DocBond Class Methods

Name

Description

DocBond

Class constructor

disp

Displays information about this object and calls the DocAsset disp method

calc_value

Utility function to calculate the bond's current value

Specifying the Base Class

The < symbol specifies the DocAsset class as the base class for the DocBond class in the classdef line:

classdef DocBond < DocAsset

Property Definition Block

The following code block shows how the properties are defined:

properties
   FaceValue = 0;
   Yield = 0;
   CurrentBondYield = 0;
end

Using the DocBond Class

Suppose you want to create a record of an asset that consists of an xyzbond with a face value of $100 and a current yield of 4.3%. The current yield for the equivalent bonds today is 6.2%, which means that the market value of this particular bond is less than its face value.

Call the DocBond constructor function with the following arguments:

  • Bond name or description

  • Bond's face value

  • Bond's interest rate or yield

  • Current interest rate being paid by equivalent bonds (used to calculate the current value of the asset)

For example, this statement:

b = DocBond('xyzbond',100,4.3,6.2);

creates a DocBond object, b, that contains information about a bond asset xyzbond with a face value of $100, a yield of 4.3%, and also contains information about the current yield of such bonds (6.2% in this case) that is used to calculate the current value.

    Note   The calculations performed in this example are intended only to illustrate the use of MATLAB classes and do not represent a way to determine the actual value of any monetary investment.

The DocBond Constructor Method

The DocBond constructor method requires four arguments. It also supports the no argument syntax by defining default values for the missing input arguments:

function b = DocBond(description,face_value,yield,current_yield)
   if nargin ~= 4
      description = '';
      face_value = 0;
      yield = 0;
      current_yield = 0;
   end
   market_value = DocBond.calc_value(face_value,yield,current_yield);
   b = b@DocAsset(description,'bond',market_value);
   b.FaceValue = face_value;
   b.Yield = yield;
   b.CurrentBondYield = current_yield;
end % DocBond

The calc_value Method

The DocBond class determines the market value of bond assets using a simple formula that scales the face value by the ratio of the bond's interest yield to the current yield for equivalent bonds.

Calculation of the asset's market value requires that the yields be nonzero, and should be positive just to make sense. While the calc_value method issues no errors for bad yield values, it does ensure bad values are not used in the calculation of market value.

The asset's market value is passed to the DocAsset base-class constructor when it is called within the DocBond constructor. calc_value has its Static attribute set to true because it does not accept a DocBond object as an input argument. The output of calc_value is used by the base-class (DocAsset) constructor:

methods (Static)
   function market_value = calc_value(face_value,yield,current_yield)
      if current_yield <= 0 || yield <= 0
         market_value = face_value;
      else
         market_value = face_value*yield/current_yield;
      end
   end % calc_value
end % methods

The DocBond disp Method

When you issue this statement (without terminating it with a semicolon):

b = DocBond('xyzbond',100,4.3,6.2)

the MATLAB runtime looks for a method in the @DocBond folder called disp. The disp method for the DocBond class produces this output:

Description: xyzbond
Date: 17-Nov-1998
Type: bond
Current Value:  $69.35
Face value of bonds: $100
Yield: 4.30%

The following function is the DocBond disp method. When this function returns from the call to the DocAsset disp method, it uses fprintf to display the FaceValue, Yield, and CurrentValue property values on the screen:

function disp(b)
   disp@DocAsset(b) % Call DocAsset disp method
   fprintf('Face value of bonds: $%g\nYield: %3.2f%%\n',...
      b.FaceValue,b.Yield);
end % disp

Designing a Class for Savings Assets

The DocSavings class is similar to the DocStock and DocBond class in that it is derived from the DocAsset class to represent a specific type of asset.

Displaying the Class Files

Open the DocSavings class definition file in the MATLAB Editor.Open the DocSavings class definition file in the MATLAB Editor.

To use the class, create a folder named @DocSavings and save DocSavings.m to this folder . The parent folder of @DocSavings must be on the MATLAB path.

Summary of the DocSavings Class

This class is defined in one file, DocSavings.m, which you must place in an @ folder of the same name. The parent folder of the @DocSavings folder must on the MATLAB path. See the addpath function for more information.

The following table summarizes the properties defined for the DocSavings class.

DocSavings Class Properties

Name

Class

Default

Description

InterestRate

double

''

Current interest rate paid on the savings account

Properties Inherited from the DocAsset Class

Description

char

''

Description of asset

CurrentValue

double

0

Current value of asset

Date

char

date

Date when record is created (set by date function)

Type

char

''

The type of asset (stock, bond, savings)

The following table summarizes the methods for the DocSavings class.

DocSavings Class Methods

Name

Description

DocSavings

Class constructor

disp

Displays information about this object and calls the DocAsset disp method

Specifying the Base Class

The < symbol specifies the DocAsset class as the base class for the DocBond class in the classdef line:

classdef DocSavings < DocAsset

Property Definition Block

The following code shows how the property is defined:

properties
	   InterestRate = 0;
end

Using the DocSavings Class

Suppose you want to create a record of an asset that consists of a savings account with a current balance of $1000 and an interest rate of 2.9%.

Call the DocSavings constructor function with the following arguments:

  • Bank account description

  • Account balance

  • Interest rate paid on savings account

For example, this statement:

sv = DocSavings('MyBank',1000,2.9);

creates a DocSavings object, sv, that contains information about an account in MyBank with a balance of $1000 and an interest rate of 2.9%.

The DocSavings Constructor Method

The savings account interest rate is saved in the DocSavings class InterestRate property. The asset description and the current value (account balance) are saved in the inherited DocAsset object properties.

The constructor calls the base class constructor (DocAsset.m) to create an instance of the object. It then assigns a value to the InterestRate property. The constructor supports the no argument syntax by providing default values for the missing arguments.

function s = DocSavings(description,balance,interest_rate)
   if nargin ~= 3
      description = '';
      balance = 0;
      interest_rate = 0;
   end
   s = s@DocAsset(description,'savings',balance);
   s.InterestRate = interest_rate;
end % DocSavings

The DocSavings disp Method

When you issue this statement (without terminating it with a semicolon):

sv = DocSavings('MyBank',1000,2.9)

the MATLAB runtime looks for a method in the @DocSavings folder called disp. The disp method for the DocSavings class produces this output:

Description: MyBank
Date: 17-Nov-1998
Type: savings
Current Value:  $1000.00
Interest Rate: 2.90%

The following function is the DocSaving disp method. When this function returns from the call to the DocAsset disp method, it uses fprintf to display the Numshares and SharePrice property values on the screen:

function disp(b)
   disp@DocAsset(b)  % Call DocAsset disp method
   fprintf('%s%3.2f%%\n','Interest Rate: ',s.InterestRate);
end % disp
Was this topic helpful?