A class can be defined using classdef
in an .m
file with the same name as the class. The file can contain the classdef
...end
block and local functions for use within class methods.
The most general MATLAB class definition has the following structure:
classdef (ClassAttribute = expression, ...) ClassName < ParentClass1 & ParentClass2 & ...
properties (PropertyAttributes)
PropertyName
end
methods (MethodAttributes)
function obj = methodName(obj,arg2,...)
...
end
end
events (EventAttributes)
EventName
end
enumeration
EnumName
end
end
MATLAB Documentation: Class attributes, Property attributes, Method attributes, Event attributes, Enumeration class restrictions.
A class called Car
can be defined in file Car.m
as
classdef Car < handle % handle class so properties persist
properties
make
model
mileage = 0;
end
methods
function obj = Car(make, model)
obj.make = make;
obj.model = model;
end
function drive(obj, milesDriven)
obj.mileage = obj.mileage + milesDriven;
end
end
end
Note that the constructor is a method with the same name as the class. <A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. A constructor is an instance method that usually has the same name as the class, and can be used to set the values of the members of an object, either to default or to user-defined values.>
An instance of this class can be created by calling the constructor;
>> myCar = Car('Ford', 'Mustang'); //creating an instance of car class
Calling the drive
method will increment the mileage
>> myCar.mileage
ans =
0
>> myCar.drive(450);
>> myCar.mileage
ans =
450