Setting object properties from a class method
Show older comments
Hi,
I'm exploring OOP with matlab and have the following code:
% method declaration
function Update(obj, Time)
obj.DeltaTime = Time; % saves time parameter to a class-wide property
obj.Height = obj.Height + obj.DeltaHeight; % new tank height
end
DeltaTime, Height are public properties of the class this sits inside. I call the method using the following syntax:
% method call
Update(TankA, 7)
There are other methods that use DeltaTime to calculate DeltaHeight. These all work perfectly fine. However, calling this method doesn't change the DeltaTime property, nor set Height to its new value. I don't get any errors thrown when the code runs, so have no idea why its not working as I expect it to. I don't know how to pass the values to the properties as method outputs either:
% using method outputs
function [DeltaTime, Height] = Update(obj,Time)
DeltaTime = Time;
Height = obj.Height + DeltaHeight;
end
Ideally I want DeltaTime, DeltaHeight to be private properties, and not manipulated directly from a separate file. Can someone please give me an idea what could be causing this?
Accepted Answer
More Answers (1)
Image Analyst
on 11 Aug 2012
What is obj? Is it some other object? It's not the same object is it? If it is, why aren't you simply doing:
function Height = Update(Time)
Height = Height + Time;
end
You don't even need DeltaTime since it's the same as Time that you passed in.
2 Comments
Manish Makwana
on 11 Aug 2012
Robert Jack
on 17 Apr 2018
I don't understand why this is the accepted answer. In my view the answer by per isakson is better. I'm troubled why an mvp is asking what 'obj' is when the context is clearly that of class properties.
Categories
Find more on Methods in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!