필터 지우기
필터 지우기

How to create a subclass to built-in class?

조회 수: 4 (최근 30일)
Martin Moennigmann
Martin Moennigmann 2017년 2월 21일
답변: Philip Borghesani 2017년 2월 21일
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
Martin Moennigmann
Martin Moennigmann 2017년 2월 21일
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

댓글을 달려면 로그인하십시오.

답변 (1개)

Philip Borghesani
Philip Borghesani 2017년 2월 21일
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

카테고리

Help CenterFile Exchange에서 Class Introspection and Metadata에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by