Reputation:
I have 2 classes:
classdef Car
properties
make;
end
methods
function obj=Car(MyMake)
obj.make=MyMake;
end
end
end
and
classdef Engine
properties
power;
end
methods
function obj=Engine(bhp)
obj.power=bhp;
end
end
end
How should I nest the Engine class within the Car class?
My idea is to do something along the lines of Honda.Engine.Valve.getDiameter()
In Python, all I would need to do is indent, I am not sure what to do here.
Upvotes: 4
Views: 9519
Reputation: 4612
I don't believe you can nest classes in Matlab. However, you can still achieve (more or less) your desired outcome using regular classes and assigning the "nested class" as a property of the "containing class."
For example:
classdef Nested
methods
function this=Nested()
% Yep.
end
end
end
classdef Box
properties
nested
end
methods
function this=Box()
this.nested = Nested();
end
end
end
This won't allow the "nested" class to access the properties of the "containing" class, but it can provide the same nested access as you described.
For more information, see http://www.mathworks.com/help/matlab/matlab_oop/saving-class-files.html. For example, this page states:
Create a single, self-contained class definition file in a folder on the MATLAB® path. The name of the file must match the class (and constructor) name and must have the .m extension. Define the class entirely in this file.
So, nested classes would violate this syntax because they are not contained in their own file on the Matlab path.
I haven't worked with Matlab packages before, but you may be able to work out your particular organization and functionality using packages. See http://www.mathworks.com/help/matlab/matlab_oop/scoping-classes-with-packages.html
Good luck!
Upvotes: 1