Reputation: 293
In Matlab (2017a), subclasses cannot restrict access to inherited methods that are declared abstract in the abstract superclass. Why wouldn't this be allowed? A small example:
super.m
classdef (Abstract) super
methods (Abstract)
out = fun(obj,in)
end
end
sub.m
classdef sub < super
properties
prop
end
methods (Access='private') %remove the access restriction to run without errors
function out = fun(obj,in)
out = obj.prop * in;
end
end
end
testInheritance.m
instance = sub;
Execution of testInheritance.m results in the following error message:
Error using sub Method 'fun' in class 'sub' uses different access permissions than its superclass 'super'.
Upvotes: 1
Views: 598
Reputation: 30165
They don't have to be public, but they have to be accessible by the sub and super class, and as the error states they must be the same. So you've got 2 issues:
You want to set Access = protected
, which means only the super class and sub classes have visibility of the function, therefore the have the same access permissions, can specify their own behaviour and the function is hidden from other objects.
Here are the Access
options, with definitions from the documentation:
So your classes become:
classdef (Abstract) super
methods (Abstract = true, Access = protected)
out = fun(obj,in)
end
end
classdef sub < super
properties
prop
end
methods (Access = protected)
function out = fun(obj,in)
out = obj.prop * in;
end
end
end
Note that the syntax is Access = protected
, not Access = 'protected'
as you showed.
Upvotes: 1
Reputation: 25160
Changing the access properties of a method that is declared 'public'
in the base class to make it not accessible in the derived class (which is what your code is attempting to do) is not permitted because it would violate the Liskov Substitution Principle.
In other words, by changing the method fun
from public
to private
, then a client cannot use an instance of sub
as if it was an instance of super
.
Upvotes: 1