I’m starting out with object-oriented programming in MATLAB, and I’m confused on how to best pass objects to other objects, as MATLAB doesn’t feature static type definitions.
I have three different classes, all of which include some constants. Now, I want to use the constants defined in two of the classes in the methods of the third class – how should I do this? The classes are in no hierarchy.
So, I’m looking for something like #include in C++.
Problem illustrated below. How to write “*Object1” and “*Object2” references to access const1 and const2?
classdef Object1
properties (Constant)
const1 = 100;
end
methods
function Obj1 = Object1()
end
end
classdef Object2
properties (Constant)
const2 = 200;
end
methods
function Obj2 = Object2()
end
end
classdef Object3
properties (Immutable)
property3
end
methods
function Obj3 = Object3()
Obj3.property3 = *Object1.const1 + *Object2.const2;
end
end
Just remove the asterisks, and I think you have what you need.
There are a couple of other syntax errors in your code (replace
ImmutablewithSetAccess = immutable, and add missingends to theclassdefs), but once I made those changes, I get:In general, to reference a
Constantproperty from another class, just prefix the property with the class name (and possibly package name, if the classes are in a package).