user1574598
user1574598

Reputation: 3881

MatLab OOP Setting a Property via a Utility Method

I'm trying to change a property in a class called houses via a utility method which is Static. I'm getting terribly confused with the reference obj as I don't know when and where it should be used. I am trying to bypass the constructor method so I can access the setProperty method, but I am getting errors such as too many output arguments. I've tried passing in obj as well as x, but I get similar errors. However, I can change the property a if I pass in a value to the constructor method.

classdef houses

properties
    a;
end

methods

    % constructor method
    function obj = houses()
    end
end

methods (Static)

    function setProperty(x)
        obj.a = x;
    end

end

end

Upvotes: 0

Views: 146

Answers (2)

nicolas
nicolas

Reputation: 3280

A static method is not typically supposed to access an object (hence it does not have access to obj). If you want to modify a static propperty (shared by all objects, and the class itself), you can use something like:

classdef houses
    properties (Static)
        a;
    end
    methods
        % constructor method
        function obj = houses()
        end
    end
    methods (Static)
        function setProperty(x)
            houses.a = x;
        end
    end
end

Regarding obj, it is the 1st argument of every methods (non static). So when you do:

o = myClass();
o.myMethod(args);

Matlab will see this as:

myMethod(o, args);

So when you define the method, you have to put obj as the 1st argument (in fact you can choose any name, it does not have to be obj).

Upvotes: 1

gire
gire

Reputation: 1105

In general, you should not use static methods to set properties of a class. If your property is public, then you can use a static method but it is highly recommended that you do not. If your property is private/protected, then you definitely cannot use a static method to modify it.

Your class should look like this then (I took the liberty of stating explicitly the access properties of each block):

classdef houses

    properties (Access = private)
        a;
    end

   methods (Access = public)

       % constructor method
       function obj = houses()
       end

       function SetA(obj, a)
          obj.a = a;
       end

       function DoSomething(obj, more_parameters)
           % Lengthy stuff here
       end

   end

end

Now, regarding your question about obj: the answer is you must pass obj as the first argument of every instance method. The variable obj refers to the current instance of the class in a generic way. See for example the method DoSomething.

Static methods do not have access to any of the properties of the class, unless public. As such, when declaring a static method, you should not pass the obj variable.

Last thing: always use explicit access modifiers for your properties and methods. It will save you some headaches.

Upvotes: 2

Related Questions