Reputation: 271
Is it possible define more than one class constructor in Matlab? If yes, how?
Upvotes: 26
Views: 22942
Reputation: 16195
No. The constructors in OOP matlab are very restricted compared to other languages. It is not explicitly stated in the documentation AFAIK that you can have multiple constructors, but it refers to the constructor of a class in the singular throughout the documentation.
https://www.mathworks.com/help/matlab/matlab_oop/class-constructor-methods.html
Upvotes: 3
Reputation: 664
The answer of Pursuit works, but a user not familiar to the function can't see how many arguments are needed or what they are for. I would recommend this:
methods (Access = public)
function self = Bicycle(startCadence, startSpeed, startGear)
if nargin>2
self.gear = startGear;
else
self.gear = 1;
end
self.cadence = startCadence;
self.speed = startSpeed;
end
end
If you now type "Bicycle(" and wait you can see at least the three arguments. The second possibility is not shown though. It seems possible (e.g. for plot) but I don't know how to do this.
Upvotes: 6
Reputation: 12345
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
Upvotes: 36
Reputation: 74940
Each class has only one constructor, and each .m-file can only contain one class definition.
If you want to have a class with slight differences depending on input, you can use properties that define switches that are recognized by the class methods. If you want to have very different classes depending on input, you can create a generateClass
-function that will call either one or the other class defined in different files. Of course, if these different classes have lots of common methods and properties, you can create both as subclasses to a common superclass.
Upvotes: 4