How to override inherited methods?

20 次查看(过去 30 天)
classdef superClass < matlab.mixin.SetGet % SuperClass
properties
prop1 = [];
prop2 = [];
end
methods
function obj = superClass( )
obj.set( 'prop1', 'Hello!' );
obj.set( 'prop2', 'My name is' );
end
function set.prop1( self, value ) % Method that I want to override.
self.prop1 = value;
end
function set.prop2( self, value ) % I don't want to override all of them.
self.prop2 = value;
end
end
end
classdef subClass < superClass
properties
prop3 = [];
end
methods
function obj = subClass( )
obj.set( 'prop1', 'Hello' );
obj.set( 'prop2', 'My name is' );
obj.set( 'prop3', 'Dom.' );
end
function set.prop1( self, value ) % Override here, somehow...
value = strcat( value, ', World!' )
self.prop1 = value;
end
function set.prop3( self, value )
self.prop3 = value
end
end
end
Is there a way to override set.prop1() in 'subClass'? Do I need to change the methods attributes of the superClass set method, or the property attributes in 'subClass'/'superClass'? Here is the error when I try to define a subClass() instance:
----------------------------
"Error using subClass
Error: File: subClass.m Line: 1 Column: 10
Cannot specify a set function for property 'prop1' in class 'subClass', because that property is
not defined by that class."
----------------------------
If you create a 'prop1' property in 'subClass' and then again try to define an instance, then I get this error:
----------------------------
"Error using subClass
Cannot define property 'prop1' in class 'subClass' because the property has already been defined in the superclass
'superClass'."
----------------------------

采纳的回答

Steven Lord
Steven Lord 2019-12-5
You can't do what you asked. If you could, you could relax the property setting validation to the point where your subClass instance wouldn't be a valid superClass instance.
You may be able to do what you want, however. Your superClass's property setter could call a normal instance method that subClass could overload. See the trustedSubclassSetterHelper methods in the attached superClass495080 and subClass495080. That helper doesn't actually set the property (otherwise you get into a loop) but merely provides the updated value. This means that the value would have to be something both superClass495080 (in set.prop1) and subClass495080 (in trustedSubclassSetterHelper) accept as a valid value.
>> Q = superClass495080
Q =
superClass495080 with properties:
prop1: 'Hello!'
prop2: 'My name is'
>> Q2 = subClass495080
Q2 =
subClass495080 with properties:
prop3: 'Dom.'
prop1: 'Hello World!'
prop2: 'My name is'

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Subclass Definition 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by