classdef - Class definition keywords - MATLAB (original) (raw)

Class definition keywords

Syntax

classdef (Attributes) ClassName < SuperclassNames properties (Attributes) ... end methods (Attributes) ... end events (Attributes) ... end enumeration ... end end

Description

classdef ... end encloses a class definition. The first line of the classdef block has this syntax:

classdef (Attribute1 = value1, Attribute2 = value2,...) ClassName < SuperclassName1 & SuperclassName2 & ...

The classdef block can include one or more of these class member blocks:

Examples

collapse all

Class Representation of Electric Motor

The Motor class stores the current speed of an electric motor and provides basic functionality for starting and stopping the motor. The class inherits from the ElectricVehicleComponent superclass and includes a property block and a method block.

classdef Motor < ElectricVehicleComponent

properties
    CurrentSpeed = 0
    SpeedRange = [0, 180]
end

methods
    function motor = start(motor,speed)
        arguments
            motor (1,1) Motor
            speed (1,1) {mustBeReal, mustBeNonnegative}
        end
        if motor.CurrentSpeed > 0
            error("Motor:start:MotorAlreadyRunning",...
                "Cannot start a motor that is already running.")
        end
        motor.CurrentSpeed = speed;   
    end
    
    function motor = stop(motor)
        if motor.CurrentSpeed == 0
            error("Motor:start:MotorNotRunning",...
                "Cannot stop a motor that is not running.")
        end
        motor.CurrentSpeed = 0;
    end
end

end

Tips

Version History

Introduced in R2008a