Presentation is loading. Please wait.

Presentation is loading. Please wait.

OOP: Creating a Class Topics More OOP concepts

Similar presentations


Presentation on theme: "OOP: Creating a Class Topics More OOP concepts"— Presentation transcript:

1 OOP: Creating a Class Topics 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.

2 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 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

3 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) Inherited Fields: descriptor date current_value STOCK Fields: num_shares share_price asset STOCK class Inherited Fields: descriptor date current_value BOND Fields: int_rate asset BOND class Inherited Fields: descriptor date current_value SAVINGS Fields: int_rate asset SAVINGS class Inherited Fields: descriptor date current_value PROP Fields: mort_rate asset PROP class

4 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

5 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.current_value = varargin{2}; a = class(a,'asset'); % create the object otherwise error('ASSET: wrong number of arguments.') 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

6 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:

7 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).

8 Examples with our new class
Try the following examples: Make sure you have created a subdirectory 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: >> b=asset(a); >> whos Name Size Bytes Class a x asset object b x asset object Grand total is 92 elements using 2428 bytes >> c=asset Descriptor: none Current Value: Creates an object Creates a copy of a Creates an empty object

9 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: >> class(x) ans = asset >> whos Name Size Bytes Class a x asset object b x asset object c x asset object x x asset object Grand total is 88 elements using 1664 bytes Using an index simply references the entire object (x is a copy of a)

10 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.']); 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)

11 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 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.') NOTE: you should include code to check for proper values as well.

12 Example using get and set
Try the following examples… Make sure you have created a subdirectory 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: >> get(a,'Descriptor') ans = My asset >> a=set(a,'CurrentValue',2000) Current Value: >> a=set(a,'Date',datestr(datenum(date)+1)) Date: 11-Oct-2002 Get a property value Set a property value Change date…

13 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:

14 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 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 Fall 2006

15 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

16 Summary Learning Objectives Action Items 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


Download ppt "OOP: Creating a Class Topics More OOP concepts"

Similar presentations


Ads by Google