rize
rize

Reputation: 859

Passing objects to other objects in MATLAB

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

Upvotes: 1

Views: 209

Answers (1)

Sam Roberts
Sam Roberts

Reputation: 24127

Just remove the asterisks, and I think you have what you need.

There are a couple of other syntax errors in your code (replace Immutable with SetAccess = immutable, and add missing ends to the classdefs), but once I made those changes, I get:

a = Object3
a = 
  Object3

  Properties:
    property3: 300
  Methods

In general, to reference a Constant property from another class, just prefix the property with the class name (and possibly package name, if the classes are in a package).

Upvotes: 2

Related Questions