Consider the following simple class hierarchy:
A.m
classdef A < handle
methods (Access = protected) %# protected vs. private
function foo(obj)
disp('class A')
end
end
end
B.m
classdef B < A
methods (Access = public)
function foo(obj)
disp('class B')
end
end
end
Class B inherits from class A and is supposed to override the protected foo method as public.
If we try to instantiate the derived class, we get the following error:
>> b=B();
Error using B
Method 'foo' in class 'B' uses different access permissions than its superclass 'A'.
The weird thing is if foo was defined as private method in the superclass A, the code works just fine when we invoke the overridden method:
>> clear classes
>> b=B(); b.foo()
class B
So is this a limitation/bug in MATLAB OOP implementation, or is there a good reason behind this behavior? (Code was tested on R2012b)
As a comparison, in Java the rules state that you cannot reduce visibility of a method in the sub-class, but you can increase it, where:
(weakest) private < package < protected < public (strongest)
