How to create a subclass to built-in class?

2 views (last 30 days)
Martin Moennigmann
Martin Moennigmann on 21 Feb 2017
Answered: Philip Borghesani on 21 Feb 2017
I fail to create a subclass to the built-in class ss (state space system, part of control systems toolbox). The constructor for the class, which involves a call to the superclass constructor, returns an instance. This instance has the method 'new_method' in that the methods() function lists it, but when I call the method on the instance, it is not found by the interpreter Here is a very short version of a code that generates the described problem:
classdef my_subclass < ss
properties
my_prop
end
methods
function obj= my_subclass(the_value)
% Constructor.
obj= obj@ss(); % call to superclass constructor not required,
% but makes code clearer
obj.my_prop= the_value;
end
function obj= new_method(obj, the_value)
% Simple example for a method that exists according to the
% methods() function, but cannot be called.
obj.my_prop= the_value;
end
end
end
Instantiation works fine:
>> instance= my_subclass(3)
instance =
Empty state-space model.
>> instance.my_prop
ans =
3
>>
The new method exists:
>> methods(instance)
Methods for class my_subclass:
... new_method % The result of methods is too long to show it here, but it does contain 'new_method'.
Calling 'new_method' results in an error:
>> instance.new_method(4)
Error using InputOutputModel/subsref (line 44)
No property of the class "my_subclass" matches the string "new_method". Use PROPERTIES to get the list of properties for this class.
>>
  1 Comment
Martin Moennigmann
Martin Moennigmann on 21 Feb 2017
Note that the following matlab documentation pages are related, but do not provide an answer to my question (at least not to me): Subclasses of Built-In Types with Properties Subclasses of MATLAB Built-In Types

Sign in to comment.

Answers (1)

Philip Borghesani
Philip Borghesani on 21 Feb 2017
You did it correctly in general but the ss class should probably be marked as Sealed, I recommend not subclassing it. Only properties of an ss class and its children can be accessed with dot indexing, to call a method use a direct method call:
% instance.new_method(4) % will fail
new_method(instance,4) % correctly calls new_method

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!