Вы находитесь на странице: 1из 14

The simplest form of a class definition is

classdef (Attributes) ClassName < SuperClass

properties (Attributes)
PropertyName1
PropertyName2
...
end

methods (Attributes)
function [obj = ] methodName(obj,arg1,arg2, ...)
...
end
end
*********EXAMPLE-1********
classdef vector
properties
x; % X value of vector
y; % Y value of vector
end
end

****This class is saved in a file named vector.m***.


***An object of class vector are***

a = vector
a =
vector with properties:
x: []
y: []

a.x = 2;
� a.y = 3;
� a
a =
vector with properties:
x: 2
y: 3

Values can also be accessed through the dot operator:


� a.x
ans =
2
create another object of vector
***************************************
Adding Methods to a Class
*****************************************
Methods can be added to a class by defining them in a methods block within the
class definition.

constructor:
A constructor is a method that initializes objects of the
class when they are instantiated.

A constructor is a method that has the same name as the class.


There can be any number of input arguments to a constructor, but the single
output of the constructor is an object of the type being created.
% Declare the constructor
function v = vector(a,b)
v.x = a;
v.y = b;
end

**************************************************
A version of the vector class constructor that also supports the default case is
shown below:
*************************************************
% Declare the constructor
function v = vector(a,b)
if nargin < 2
v.x = 0;
v.y = 0;
else
v.x = a;
v.y = b;
end
end
**************************
a = vector(3,4)
a =
vector with properties:
x: 3
y: 4
� b = vector(-12,5)
b =
vector with properties:
x: -12
y: 5
� c = vector
c =
vector with properties:
x: 0
y: 0
**************************
ordinary instance methods
**************************
Instance methods are methods that use or modify the instance variables stored in
objects created from the class.

They are functions with a special syntax.


*****************************************

Declare a method to calculate the length


% of the vector.
function result = length(this)
result = sqrt(this.x.�2 + this.y.�2);
end

Method add sums the contents of the current vector object this and another vector
object obj2, with the result stored in output object obj.

% Declare a method to add two vectors together


function obj = add(this,obj2)
obj = vector();
obj.x = this.x + obj2.x;
obj.y = this.y + obj2.y;
end

****************************************

The vector class with these methods added is:


classdef vector
properties
x; % X value of vector
y; % Y value of vector
end
methods
% Declare the constructor
function v = vector(a,b)
if nargin < 2
v.x = 0;
v.y = 0;
else
v.x = a;
v.y = b;
end
end
% Declare a method to calculate the length
% of the vector.
function result = length(this)
result = sqrt(this.x.�2 + this.y.�2);
end
% Declare a method to add two vectors together
function obj = add(this,obj2)
obj = vector();
obj.x = this.x + obj2.x;
obj.y = this.y + obj2.y;
end
end
end
********************************************************
If ob is an object of type vector,
then the length would be calculated as ob.length or ob.length().
*************************************************************
The length method calculates the length of each vector from the data in the
instance variables:
� a.length
ans =
5
� b.length()
ans =
13
� c.length()
ans =
0

c = a.add(b)************
c =
vector with properties:
x: -9
y: 9
****************************************************
give another example ratnum....
***************************************************
****************************************************
Listing Class Types, Properties, and Methods
*************************************************
class(a)
ans =
vector
� properties(a)
Properties for class vector:
x
y
� methods(a)
Methods for class vector:
add length vector
**************************************************

Attributes:
Attributes are modifiers that change the behavior of classes, properties, or
methods.

They are defined in parentheses after the classdef, properties, and methods
statements in the class definition.

properties (Attribute1 = value1, Attribute2 = value2, ...)


...
end
or

properties (Attribute1 = value1)


...
end
properties (Attribute2 = value2)

methods (Attribute1 = value1, Attribute2 = value2, ...)


...
end

methods (Attribute1 = value1)


...
end
methods (Attribute2 = value2)
...
end
********************************************
Explain property attributes
*********************************************
classdef test1
% Sample class illustrating access control using attributes
properties (Access=public)
a; % Public access
b; % Public access
end
properties (GetAccess=public, SetAccess=private)
c; % Read only
end
...
end

% Declare the constructor


function obj = test1(a,b,c)
obj.a = a;
obj.b = b;
obj.c = c;
end
end
end
*******************************
obj1 = test1(1,2,3)
obj1 =
test1 with properties:
a: 1
b: 2
c: 3

It is possible to examine and modify the value of a from outside the object.
� obj1.a
ans =
1
� obj1.a = 10
obj1 =
test1 with properties:
a: 10
b: 2
c: 3

It is possible to examine but not to modify the value of c from outside the object.
� obj1.c
ans =
3
� obj1.c = -2
You cannot set the read-only property 'c' of test1.
**********************************************************
**************************************
Value Classes versus Handle Classes
************************************
Value Classes
a = vector(3,4)
a =
vector with properties:
x: 3
y: 4
� b = a
b =
vector with properties:
x: 3
y: 4
We can show that these two variables are different by assigning different values to
one of them.
� b.x = -1;
� b.y = 0;
� a
a =
vector with properties:
x: 3
y: 4
� b
b =
vector with properties:
x: -1
y: 0
**************************************
Value classes are typically used to store data values for use in calculations. For
example, the double, single, int32, and other standard MATLAB data types
are all really value classes.
**********************************************
Objects made from value classes can be deleted when they are no longer needed using
the clear command.

clear a

The command clear all would have removed all of the objects from memory
******************************************************
Handle Classes
************************************
The vector as a handle class

classdef vector_handle < handle


properties
x; % X value of vector
y; % Y value of vector
end
methods
% Declare the constructor
function this = handle_vector(a,b)
this.x = a;
this.y = b;
end
% Declare a method to calculate the length
% of the vector.
function result = length(this)
result = sqrt(this.x.�2 + this.y.�2);
end
% Declare a method to add two vectors together
function add(this,obj2)
this.x = this.x + obj2.x;
this.y = this.y + obj2.y;
end
end
end
There are two key differences in the handle version of this class. First, the class
is declared to be a subclass of handle in the class definition. Second, methods
modifying an object of this class do not return the modified object as a calling
argument.

% Declare a method to add two vectors together


function obj = add(this,obj2)
obj = vector();
obj.x = this.x + obj2.x;
obj.y = this.y + obj2.y;
end
****************************************************************
This method receives handles to the two objects as input arguments, the current
object and another object of the same class.
The method performs calculations usingthe handles, which point to the original
objects, not copies of the objects.
The two vectors are added together, with the result stored in the original vector
object (this).

The results of those calculations are automatically saved in the original object,
so no output argument needs to be returned from the function. Unlike the value
class case,
the value of the original vector is modified here.
****************************************************
a = vector_handle(3,4)
a =
vector_handle with properties:
x: 3
y: 4
� b = a
b =
vector with properties:
x: 3
y: 4

We can show that these two variables are the same by assigning different values to
one of them and seeing that the new values also show up in the other one.
� b.x = -1;
� b.y = 0;
� a
a =
vector_handle with properties:
x: -1
y: 0
� b
b =
vector_handle with properties:
x: -1
y: 0

Objects made from handle classes are automatically deleted by MATLAB when there are
no handles left that point to them. For example, following two statements
create two vector_handle objects:
� a = vector_handle(3,4);
� b = vector_handle(-4,3);
� whos
Name Size Bytes Class Attributes
a 1x1 112 vector_handle
b 1x1 112 vector_handle
If we now execute the statement
� a = b;

both handles a and b now point to the original object allocated using handle b.
The object that was originally allocated using handle a is no longer accessible,
because no handle to it exists anymore, and MATLAB will automatically delete that
object.

A user can delete a handle object at any time using the delete function with any
handle pointing to that object.

After the delete function is called, all the handles that pointed to that object
are still in memory, but they no longer point to any object.
The object that they had pointed to has been removed.
� delete(a)
� whos
Name Size Bytes Class Attributes
a 1x1 104 vector_handle
b 1x1 104 vector_handle
� a
a =
handle to deleted vector_handle
� b
b =
handle to deleted vector_handle
The handles themselves can be removed using the clear command.

*************************************************
Destructors: The delete Method
**************************************************
Modified vector_handle class
classdef vector_handle < handle
properties
x; % X value of vector
y; % Y value of vector
end
methods
...
% Declare a destructor
function delete(this)
disp('Object destroyed.');
end
end
end
Note that the delete method is optional and is not present in most classes. It is
normally included if a class has some resources (such as files) open that need to
be
released before the object is destroyed.
*******************
clear vs delete:
The clear command deletes the handle to an object, not the object itself.
***********************
If we create an object of the vector_handle class, and then clear the handle to it,
the object will be automatically destroyed because there is no longer a reference
to it.
� a = vector_handle(1,2);
� clear a
Object destroyed.

On the other hand, if we create an object of this class and assign its handle to
another variable, there will be two handles to the object. In this case, clearing
one will not
cause the object to be destroyed because there is still a valid handle to it.
� a = vector_handle(1,2);
� b = a;
� clear a
*****************************************************
The clear command deletes a handle, whereas the delete command deletes an object.
The clear command may cause the object to be deleted, too, but only if there is no
other
handle to the object.
***************************************************

1.Access Methods
2. Access Controls
********************************
Access methods can be written to ensure that only valid data is set or retrieved,
thus preventing other parts of the program from breaking the object.

Access methods have special names that allow MATLAB to identify them. The name is
always get or set followed by a period and the property name to access.

If they are defined,MATLAB will always call access methods whenever attempts are
made to use or change the properties in an object3, and the access methods can
verify the data before allowing it to be used.

If methods with these names(get or set) are defined in a methods block without
attributes, then the corresponding method will be called automatically whenever a
property is accessed. The access method will perform checks on the data before it
is used.
****************************
methods % no attributes
function set.x(this,value)
if isa(value,'double')
this.x = value;
else
disp('Invalid value assigned to x ignored');
end
end
end

a = vector_handle(3,4)
a =
vector_handle with properties:
x: 3
y: 4
a.x = 'junk'
Invalid value assigned to x ignored
a =
vector_handle with properties:
x: 3
y: 4
*****************
Access Controls
*****************
In object-oriented programming, it is often customary to declare some important
class properties to have private or protected access, so that they cannot be
modified directly by any parts of the program outside of the class.

************************
Static Methods:
************************
Static methods are declared by adding a Static attribute to the methods block in
which they are declared.

They can be accessed without creating an instance to the class first by naming the
class name followed by a period and the method name. Alternately, if an object
created from the class exists, then the static methods can be accessed by the
object reference followed by a period and the method name.

classdef Angle
...
methods(Static, Access = public)
function out = deg2Rad(in)
out = in * pi / 180;
end
function out = rad2Deg(in)
out = in * 180 / pi;
end
end
...
end

These static methods could be accessed from inside and outside the class because
their access is public. They would be invoked using the class name followed by a
dot and the method name: Angle.deg2Rad() and
Angle.rad2Deg().
a = Angle();
then the static methods could also be called using the instance object name:
a.deg2Rad() and a.rad2Deg().
*****************************************
Defining Class Methods in Separate Files
****************************************
The following example defines a class MyClass with three properties a, b,and c, and
two instance methods calc1 and calc2. The methods block contains the signature of
the two methods (the number of input arguments and output arguments), but not the
methods themselves.

classdef MyClass
...
Properties (Access = private)
a;
b;
c;
End
methods(Access = public)
function output = calc1(this);
function output = calc2(this, arg1, arg2);
end
end

There must then be two separate files calc1.m and calc2.m in the same directory
that would contain the function definitions to implement the methods.
File calc1.m
would contain the definition of function calc1:

function output = calc1(this);


...
...
end

and file calc2.m would contain the definition of function calc2:


function output = calc2(this, arg1, arg2);
...
...
end
The directory @MyClass would contain the following files:
@MyClass\MyClass.m
@MyClass\calc1.m
@MyClass\calc2.m
Note that certain methods must be in the file with the class definition. These
methods include
1. The constructor method
2. The destructor method (delete)
3. Any method that has a dot in the method name, such as get and set access
methods.

All other methods can be declared in a class definition methods block, but actually
defined in separate files in the same subdirectory.

********************************************************
Superclasses and Subclasses:
Every handle class except handle is a subclass of some other class, and the class
inherits both properties and methods from its parent class. The class can add
additional properties and methods and can also override the behavior of methods
inherited from its parent class...

Any subclass inherits the public properties and methods of the parent class. The
methods defined in a parent class can be overridden in a subclass, and the behavior
of the modified method will be used for objects of that subclass.
If a method is defined in a superclass and is not overridden in the subclass, then
the method defined in the
superclass will be used by objects of the subclass whenever the method is called.

Example:
A class Shape, describing the characteristics
of a two-dimensional shape.

A simple inheritance hierarchy. Both EquilateralTriangle


and Square inherit from Shape, and an object of either of their classes is also an
object of the Shape class

classdef Shape < handle


properties
area; % Area of shape
perimeter; % Perimeter of shape
end
methods
% Declare the constructor
function this = Shape()
% For debugging only
disp('In Shape constructor...');
this.area = 0;
this.perimeter = 0;
end
% Declare a method to calculate the area
% of the shape.
function calc_area(this)
% For debugging only
disp('In Shape method calc_area...');
this.area = 0;
end
% Declare a method to calculate the perimeter
% of the shape.
function calc_perimeter(this)
% For debugging only
disp('In Shape method calc_perimeter...');
this.perimeter = 0;
end
% Declare a method that returns info about
% the shape.
function string(this)
% For debugging only
disp('In Shape method string...');
str = ['Shape of class " ' class(this) ...
' ", area ' num2str(this.area) ...
', and perimeter ' num2str(this.perimeter)];
disp(str);
end
end
end
*************************************************************
classdef EquilateralTriangle < Shape
properties
len; % Length of side
end
methods
% Declare the constructor
function this = EquilateralTriangle(len)
% For debugging only
disp('In EquilateralTriangle constructor...');
if nargin > 0
this.len = len;
end
this.calc_area();
this.calc_perimeter();
end

Declare a method to calculate the area


% of the shape.
function calc_area(this)
% For debugging only
disp('In EquilateralTriangle method calc_area...');
this.area = sqrt(3) / 4 * this.len.�2;
end
% Declare a method to calculate the perimeter
% of the shape.
function calc_perimeter(this)
% For debugging only
disp('In EquilateralTriangle method calc_perimeter...');
this.perimeter = 3 * this.len;
end
end
end

classdef Square < Shape


properties
len; % Length of side
end
methods
% Declare the constructor
function this = Square(len)
% For debugging only
disp('In Square constructor...');
this = this@Shape();
if nargin > 0
this.len = len;
end
this.calc_area();
this.calc_perimeter();
end
% Declare a method to calculate the area
% of the shape.
function calc_area(this)
% For debugging only
disp('In Square method calc_area...');
this.area = this.len.�2;
end
% Declare a method to calculate the perimeter
% of the shape.
function calc_perimeter(this)
% For debugging only
disp('In Square method calc_perimeter...');
this.perimeter = 4 * this.len;
end
end
end

a = EquilateralTriangle(2)
In Shape constructor...
In EquilateralTriangle constructor...
In EquilateralTriangle method calc_area...
In EquilateralTriangle method calc_perimeter...
a =
EquilateralTriangle with properties:
len: 2
area: 1.7321
perimeter: 6

****************
methods(a)
Methods for class EquilateralTriangle:
EquilateralTriangle calc_perimeter
calc_area string
Note that the methods defined in this class include the unique constructor
EquilateralTriangle, the overridden methods calc_area and
calc_perimeter, and the inherited method string.

properties(a)
Properties for class EquilateralTriangle:
len
area
perimeter

b = Square(2)
In Square constructor...
In Shape constructor...
In Square method calc_area...
In Square method calc_perimeter...
b =
Square with properties:
len: 2
area: 4
perimeter: 8

Вам также может понравиться