oopmatlab

Multiple class constructor Matlab


Is it possible define more than one class constructor in Matlab? If yes, how?


Solution

  • Each class has one constructor. However ... the constructor can accept any number and type of arguments, including those based on varargin.

    So, to provide the option of a default third argument in Java you could write something like this (examples based on java documentation):

    public Bicycle(int startCadence, int startSpeed, int startGear) {
        gear = startGear;
        cadence = startCadence;
        speed = startSpeed;
    }
    public Bicycle(int startCadence, int startSpeed) {
        gear = 1;
        cadence = startCadence;
        speed = startSpeed;
    }
    

    In Matlab you could write

    classdef Bicycle < handle
        properties (Access=public)
            gear
            cadence
            speed
        end
        methods (Access = public)
            function self = Bicycle(varargin)
                if nargin>2
                    self.gear = varargin{3};
                else
                    self.gear = 1;
                end
                self.cadence = varargin{1};
                self.speed = varargin{2};
            end
        end
    end