Using MATLAB (779505), страница 96
Текст из файла (страница 96)
For the polynomexample, the output ismethods polynomMethods for class polynom:chardisplayminusplotpolynomrootsdiffdoublemtimespluspolyvalsubsrefPlotting the two polynom objects x and p calls most of these methods.x = polynom([1 0]);p = polynom([1 0 -2 -5]);plot(diff(p*p + 10*p + 20*x) - 20)22-3322MATLAB Classes and Objects6*x5 − 16*x3 + 8*x86420−2−4−6−8−222-34−1.5−1−0.500.511.52Building on Other ClassesBuilding on Other ClassesA MATLAB object can inherit properties and behavior from another MATLABobject. When one object (the child) inherits from another (the parent), the childobject includes all the fields of the parent object and can call the parent’smethods.
The parent methods can access those fields that a child objectinherited from the parent class, but not fields new to the child class.Inheritance is a key feature of object-oriented programming. It makes it easyto reuse code by allowing child objects to take advantage of code that exists forparent objects. Inheritance enables a child object to behave exactly like aparent object, which facilitates the development of related classes that behavesimilarly, but are implemented differently.There are two kinds of inheritance:• Simple inheritance, in which a child object inherits characteristics from oneparent class.• Multiple inheritance, in which a child object inherits characteristics frommore than one parent class.This section also discusses a related topic, aggregation.
Aggregation allows oneobject to contain another object as one of its fields.Simple InheritanceA class that inherits attributes from a single parent class, and adds newattributes of its own, uses simple inheritance. Inheritance implies that objectsbelonging to the child class have the same fields as the parent class, as well asadditional fields. Therefore, methods associated with the parent class canoperate on objects belonging to the child class.
The methods associated with thechild class, however, cannot operate on objects belonging to the parent class.You cannot access the parent’s fields directly from the child class; you must useaccess methods defined for the parent.The constructor function for a class that inherits the behavior of another hastwo special characteristics:• It calls the constructor function for the parent class to create the inheritedfields.22-3522MATLAB Classes and Objects• The calling syntax for the class function is slightly different, reflecting boththe child class and the parent class.The general syntax for establishing a simple inheritance relationship using theclass function ischild_obj = class(child_obj,'child_class',parent_obj);Simple inheritance can span more than one generation.
If a parent class isitself an inherited class, the child object will automatically inherit from thegrandparent class.Visibility of Class Properties and MethodsThe parent class does not have knowledge of the child properties or methods.The child class cannot access the parent properties directly, but must useparent access methods (e.g., get or subsref method) to access the parentproperties. From the child class methods, this access is accomplished via theparent field in the child structure. For example, when a constructor creates achild object c,c = class(c,'child_class_name',parent_object);MATLAB automatically creates a field, c.parent_class_name, in the object’sstructure that contains the parent object. You could then have a statement inthe child’s display method that calls the parent’s display method.display(c.parent_class_name)See “Designing the Stock Class” on page 22-45 for examples that use simpleinheritance.Multiple InheritanceIn the multiple inheritance case, a class of objects inherits attributes from morethan one parent class.
The child object gets fields from all the parent classes,as well as fields of its own.Multiple inheritance can encompass more than one generation. For example,each of the parent objects could have inherited fields from multiplegrandparent objects, and so on. Multiple inheritance is implemented in theconstructors by calling class with more than three arguments.obj = class(structure,'class_name',parent1,parent2,...)22-36Building on Other ClassesYou can append as many parent arguments as desired to the class input list.Multiple parent classes can have associated methods of the same name. In thiscase, MATLAB calls the method associated with the parent that appears firstin the class function call in the constructor function. There is no way to accesssubsequent parent function of this name.AggregationIn addition to standard inheritance, MATLAB objects support containment oraggregation.
That is, one object can contain (embed) another object as one of itsfields. For example, a rational object might use two polynom objects, one for thenumerator and one for the denominator.You can call a method for the contained object only from within a method forthe outer object. When determining which version of a function to call,MATLAB considers only the outermost containing class of the objects passedas arguments; the classes of any contained objects are ignored.See “Example - The Portfolio Container” on page 22-54 for an example ofaggregation.22-3722MATLAB Classes and ObjectsExample - Assets and Asset SubclassesAs an example of simple inheritance, consider a general asset class that can beused to represent any item that has monetary value. Some examples of an assetare: stocks, bonds, savings accounts, and any other piece of property.
Indesigning this collection of classes, the asset class holds the data that iscommon to all of the specialized asset subclasses. The individual assetsubclasses, such as the stock class, inherit the asset properties and contributeadditional properties. The subclasses are “kinds of” assets.Inheritance Model for the Asset ClassAn example of a simple inheritance relationship using an asset parent class isshown in this diagram.Asset ClassStructure Fields:descriptordatecurrent_valueStock ClassBond ClassSavings ClassInherited Fields:Inherited Fields:Inherited Fields:descriptordatecurrent_valuedescriptordatecurrent_valuedescriptordatecurrent_valueStock Fields:num_sharesshare_priceBond Fields:interest_rateassetSavings Fields:interest_rateassetassetAs shown in the diagram, the stock, bond, and savings classes inheritstructure fields from the asset class.
In this example, the asset class is usedto provide storage for data common to all subclasses and to share assetmethods with these subclasses. This example shows how to implement the22-38Example - Assets and Asset Subclassesasset and stock classes. The bond and savings classes can be implemented ina way that is very similar to the stock class, as would other types of assetsubclasses.Asset Class DesignThe asset class provides storage and access for information common to all assetchildren.
It is not intended to be instantiated directly, so it does not require anextensive set of methods. To serve its purpose, the class needs to contain thefollowing methods:• Constructor• get and set• subsref and subsasgn• displayOther Asset MethodsThe asset class provides inherited data storage for its child classes, but is notinstanced directly. The set, get, and display methods provide access to thestored data.
It is not necessary to implement the full complement of methodsfor asset objects (such as converters, end, and subsindex) since only the childclasses access the data.The Asset Constructor MethodThe asset class is based on a structure array with four fields:• descriptor – Identifier of the particular asset (e.g., stock name, savingsaccount number, etc.)• date – The date the object was created (calculated by the date command)• type – The type of asset (e.g., savings, bond, stock)• current_value – The current value of the asset (calculated from subclassdata)This information is common to asset child objects (stock, bond, and savings), soit is handled from the parent object to avoid having to define the same fields ineach child class.
This is particularly helpful as the number of child classesincreases.22-3922MATLAB Classes and Objectsfunction a = asset(varargin)% ASSET Constructor function for asset object% a = asset(descriptor, current_value)switch nargincase 0% if no input arguments, create a default objecta.descriptor = 'none';a.date = date;a.type = ‘none’;a.current_value = 0;a = class(a,'asset');case 1% if single argument of class asset, return itif (isa(varargin{1},'asset'))a = varargin{1};elseerror('Wrong argument type')endcase 2% create object using specified valuesa.descriptor = varargin{1};a.date = date;a.type = varargin{2};a.current_value = varargin{3};a = class(a,'asset');otherwiseerror('Wrong number of input arguments')endThe function uses a switch statement to accommodate three possiblescenarios:• Called with no arguments, the constructor returns a default asset object.• Called with one argument that is an asset object, the object is simplyreturned.• Called with two arguments (subclass descriptor, and current value), theconstructor returns a new asset object.22-40Example - Assets and Asset SubclassesThe asset constructor method is not intended to be called directly; it is calledfrom the child constructors since its purpose is to provide storage for commondata.The Asset get MethodThe asset class needs methods to access the data contained in asset objects.
Thefollowing function implements a get method for the class. It uses capitalizedproperty names rather than literal field names to provide an interface similarto other MATLAB objects.function val = get(a,prop_name)% GET Get asset properties from the specified object% and return the valueswitch prop_namecase 'Descriptor'val = a.descriptor;case 'Date'val = a.date;case 'CurrentValue'val = a.current_value;otherwiseerror([prop_name,' Is not a valid asset property'])endThis function accepts an object and a property name and uses a switchstatement to determine which field to access.
This method is called by thesubclass get methods when accessing the data in the inherited properties. See“The Stock get Method” on page 22-48 for an example.The Asset set MethodThe asset class set method is called by subclass set methods. This methodaccepts an asset object and variable length argument list of property name/property value pairs and returns the modified object.function a = set(a,varargin)% SET Set asset properties and return the updated objectproperty_argin = varargin;while length(property_argin) >= 2,prop = property_argin{1};val = property_argin{2};22-4122MATLAB Classes and Objectsproperty_argin = property_argin(3:end);switch propcase 'Descriptor'a.descriptor = val;case 'Date'a.date = val;case 'CurrentValue'a.current_value = val;otherwiseerror('Asset properties: Descriptor, Date, CurrentValue')endendSubclass set methods call the asset set method and require the capability toreturn the modified object since MATLAB does not support passing argumentsby reference.
















