160 likes | 350 Views
More OOP concepts An example that creates a ASSET class and shows how it might be used Extend the ASSET class to subclasses of STOCKS, BONDS and SAVINGS. OOP: Creating a Class. Topics. Learning Objectives
E N D
More OOP concepts An example that creates a ASSET class and shows how it might be used Extend the ASSET class to subclasses of STOCKS, BONDS and SAVINGS. OOP: Creating a Class Topics Learning Objectives We’re now going to introduce you to some advanced computing concepts, and we’ll illustrate a simple application that creates a new data type called an ASSET with subtypes. AE6382 Design Computing
Matlab’s Built-in Classes • Matlab’s built-in classes: • others in additional Toolboxes • You can define your own Matlab classes: • data structure (the fields) is a Matlab struct • methods (functions) are stored in special directory (@classname) that is a subdirectory of a directory in the Matlab path • a constructor is a method that is used to create an object (an instance of a class) ARRAY char NUMERIC cell structure java class function handle user class int8, uint8, int16, uint16, int32, uint32 single double sparse AE6382 Design Computing
PROP class STOCK class BOND class SAVINGS class Inherited Fields: descriptor date current_value PROP Fields: mort_rate asset Inherited Fields: descriptor date current_value STOCK Fields: num_shares share_price asset Inherited Fields: descriptor date current_value BOND Fields: int_rate asset Inherited Fields: descriptor date current_value SAVINGS Fields: int_rate asset Let’s create a Matlab class called ASSET • What is an ASSET? • it is an item with a monetary value • examples could be a stock, or a bond, or a savings account • it could also be a physical item with a monetary value (car, house) • each asset has a different way of defining its monetary value ASSET class Superclass (Parent) Properties: descriptor date current_value Subclass (Child) AE6382 Design Computing
Creating the Object: Constructors • An object must first be created using the “definition” provided in the Class (this is called instantiation) • this is like defining a new double variable (e.g., A(3,1)=5.4) • the created object now has access to all the methods that are defined in the class from which it was created • OOP languages have sophisticated ways to keep these methods and data known only inside the object or shared with one or more other classes of objects (Matlab is very simple as we’ll see later) • we’ll need a special method called a constructor to create an object (all classes must define a constructor method) • in some OOP languages, you must also provide a destructor method to remove an object when you’re done AE6382 Design Computing
ASSET Constructor function a=asset(varargin) % ASSET constructor function for asset object % Use: a = asset(descriptor, current_value) % Fields: % descriptor = string % date = date string (automatically set to current) % current_value = asset value ($) switch nargin case 0 % no arguments: create a default object a.descriptor = 'none'; a.date = date; a.current_value = 0; a = class(a,'asset'); % this actually creates the object case 1 % one arg means return same if (isa(varargin{1},'asset')) a = varargin{1}; else error ('ASSET: single argument must be of asset class.') end case 2 % create object using specified values a.descriptor = varargin{1}; a.date = date; a.current_value = varargin{2}; a = class(a,'asset'); % create the object otherwise error('ASSET: wrong number of arguments.') end varargin is a cell array with all the nargin arguments a is a structure where: a.date=date string All constructors must handle these 3 cases Polymorphism: different use of class() in constructor AE6382 Design Computing
Displaying the Object… • We need to add a method to display the object • Matlab always calls display for this purpose • we must add a method in our ASSET class… There are lots of possible variations depending on how you want the display to look… function display(a) % DISPLAY(a) displays an ASSET object str = sprintf('Descriptor: %s\nDate: %s\nCurrent Value:%9.2f',... a.descriptor, a.date, a.current_value); disp(str) - Example showing how display() is used if the semicolon is omitted in a command line >> a=asset('My asset', 1000) Descriptor: My asset Date: 29-Nov-2001 Current Value: 1000.00 AE6382 Design Computing
Comments • Every class must define a constructor and a display method (or it must be inherited from a superclass) • by convention, the constructor should handle at least the following 3 situations: • create an empty object if no arguments are supplied, or • make a copy of the object if one is supplied as the only argument. or • create a new object with specified properties. • The class() function (method) is polymorphic: • class(A) if used anywhere will return the type of variable A • class(a,’asset’) is only allowed inside a constructor and it tags a as being of class (type) ‘asset’ • class(a,’asset’,parent1) tags a as above and also it inherits methods and fields from a parent1 object (class). AE6382 Design Computing
Examples with our new class • Try the following examples: • Make sure you have created a subdirectory called @ASSET in the Matlab work directory (or a directory in the Matlab path) • copy the functions we’ve described into this directory • type in the examples at the Command prompt… >> a=asset('My asset', 1000) Descriptor: My asset Date: 10-Oct-2002 Current Value: 1000.00 >> b=asset(a); >> whos Name Size Bytes Class a 1x1 418 asset object b 1x1 418 asset object Grand total is 92 elements using 2428 bytes >> c=asset Descriptor: none Date: 10-Oct-2002 Current Value: 0.00 Creates an object Creates a copy of a Creates an empty object AE6382 Design Computing
Our Class has no Methods yet… Arithmetic operations are not defined >> a+b ??? Error using ==> + Function '+' not defined for variables of class 'asset'. >> x=a(1); >> x Descriptor: My asset Date: 29-Nov-2001 Current Value: 1000.00 >> class(x) ans = asset >> whos Name Size Bytes Class a 1x1 418 asset object b 1x1 418 asset object c 1x1 410 asset object x 1x1 418 asset object Grand total is 88 elements using 1664 bytes Using an index simply references the entire object (x is a copy of a) AE6382 Design Computing
Listing (getting) Property Values from Object • We will want to extract property values from an object GET is a “standard” name function val = get(a, prop_name) % GET: Get asset properties from specified object if ~ischar(prop_name), error('GET: prop_name must be string.'), end prop_name = lower(prop_name(isletter(prop_name))); %remove nonletters if (length(prop_name) < 2) error('GET: prop_name must be at least 2 chars.') end switch prop_name(1:2) case'de' val = a.descriptor; case'da' val = a.date; case'cu' val = a.current_value; otherwise error(['GET: ',prop_name,' is not a valid asset property.']); end Must check for valid input Note the tricky way to remove all nonletters in the string ! You can test for some or all of the property name string (shortens how much the user must type) AE6382 Design Computing
Changing Property Values in an Object • W must be able to change the values of some of the properties in the object: • we’ll create a method (function) called get() for this • it will be part of the asset class located in the @ASSET directory function a = set(a,varargin) % SET: set asset properties and return updated object. More than one % property can be set but must provide: ‘prop_name’, value pairs if rem(nargin,2) ~= 1 error('SET: prop_name, values must be provided in pairs.') end for k=2:2:nargin-1 prop_name = varargin{k-1}; if ~ischar(prop_name), error('SET: prop_name must be string.'), end prop_name = lower(prop_name(isletter(prop_name))); %remove nonletters value = varargin{k}; switch prop_name(1:2) case'de' a.descriptor = value; case'da' a.date = value; case'cu' a.current_value = value; otherwise error('SET: invalid prop_name provided.') end end NOTE: you should include code to check for proper values as well. AE6382 Design Computing
Example using getandset • Try the following examples… • Make sure you have created a subdirectory called @ASSET in the Matlab work directory (or a directory in the Matlab path) • copy the functions we’ve described into this directory • type in the examples at the Command prompt… >> a Descriptor: My asset Date: 10-Oct-2002 Current Value: 1000.00 >> get(a,'Descriptor') ans = My asset >> a=set(a,'CurrentValue',2000) Descriptor: My asset Date: 10-Oct-2002 Current Value: 2000.00 >> a=set(a,'Date',datestr(datenum(date)+1)) Descriptor: My asset Date: 11-Oct-2002 Current Value: 2000.00 Get a property value Set a property value Change date… AE6382 Design Computing
Important Notes • We didn’t need a return value using get, but… • We MUST show the same object we’re modifying as the return value for set • this is because Matlab does not allow us to modify the values of the arguments in a function and have them returned to the calling workspace!!! • We could use the assignin() function to avoid this problem (see also the evalin() function for another variation on this) • Other OOP languages don’t have this problem… This is perhaps the most awkward, inelegant aspect of OOP in Matlab. It is VERY non-standard when compared to Java, C++ or SmallTalk, etc. set() must return the same object as provided in the argument list >> a=set(a,'CurrentValue',2000) Descriptor: My asset Date: 29-Nov-2001 Current Value: 2000.00 AE6382 Design Computing
Summary… • OOP has let us create an entirely new data type in Matlab • this is done by creating a class to define this data type • we must also create all the methods (functions) that can be used with this special data type • the internal details are hidden inside the class • What else could we do with this new class? • create a subclass of assets called STOCK that will include fields for data specific to a stock asset (see next slide) • the methods for this new subclass will be in the @STOCK subdirectory • we could continue to create subclasses for BOND and PROPERTY types of assets, each with their own extended data values and perhaps new methods. AE6382 Design Computing
Where to from here? • With only a little modification we can create an entirely new subclass that is based on our STOCK class • We can do this by specifying that our new class will inherit the structure and methods from a parent or superclass (or from several parent classes). • This is called “inheritance” and is an important feature of OOP. • Consider a BOND class • It has an identical structure to a STOCK, • But there will be different properties • We will create new display, get and set methods • We will use the set and get methods from ASSET to modify properties in the parent AE6382 Design Computing
Summary Learning Objectives • OOP concepts • ASSET & STOCK classes • Summary • Action Items • Review the lecture • Perform the exercises • See if you can create the BOND class and get it working like we did for the STOCK class. • Consider how this might be extended to other applications AE6382 Design Computing