sajad
sajad

Reputation: 2174

Multiple fields of specific class in another class

I am developing an object oriented program in MATLAB. I have a class called MyNode and a class called MyService as you see here:

classdef MyService
     % ......

end

classdef MyNode        
    properties
        MyNode     % List of neighbor Nodes

        MyService  % List of services that I request
        MyService  % List of services that I provide
    end

end

I want the class MyNode to have two instances of the MyService class, but I also want to have a list of MyNode objects in its definition. I know this code is not correct in MATLAB. How can I do that?

Upvotes: 0

Views: 115

Answers (1)

Dev-iL
Dev-iL

Reputation: 24169

You are confusing property names with property class specifications (which are not required in MATLAB). In the code you wrote, you end up having fields with the name of MyNode and MyService, letting MATLAB assume what the datatype should be (probably double when uninitialized, and not what you wanted).

To fix this, please read the documentation page on validating property values. You will find that the way to specify the class for properties/fields is done using the following syntax: enter image description here

In you case, this might look like this:

classdef MyNode        
    properties
        neighbors(:,1) MyNode    % List of neighbor Nodes
%       ^ name    ^ size   ^ class
        rService(1,1) MyService  % List of services that I request
        pService(1,1) MyService  % List of services that I provide
    end    
end

I would also advise adding some constructors to your classes.

Finally, I'd like to mention that I tested the above recursive class definition in R2018a. If your MATLAB version is fairly old (before R2016a), you can only use the syntax mentioned here, roughly:

<varName>@<class> <scalar/vector/matrix> = <initial value>;

Upvotes: 1

Related Questions