How to override inherited methods?
Show older comments
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'."
----------------------------
Accepted Answer
More Answers (0)
Categories
Find more on Properties in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!