Consider the following simple class hierarchy:
classdef A < handle
methods (Access = protected) %# protected vs. private
function foo(obj)
disp('class A')
end
end
end
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)
classdef Syntax Class definitions are blocks of code that are delineated by the classdef keyword at the beginning and the end keyword at the end. Files can contain only one class definition.
Building on the Handle Class Use the handle class as a superclass to implement subclasses that inherit handle behavior. MATLAB® defines several classes that derive from the handle class. These classes provide specialized functionality to subclasses.
You cannot derive a subclass from any two or more classes that define incompatible class members. Here are various situations where you can resolve name and definition conflicts.
Methods with Access Lists Classes granted access to a method can: Call the method using an instance of the defining class. Define their own method with the same name (if not a subclass). Override the method in a subclass only if the superclass defining the method includes itself or the subclass in the access list.
This appears to be a limitation of Matlab. I've tried all combinations of attributes. Matlab throws errors whenever the attributes are different, except when the method of A is private, in which case the attributes in B don't matter.
In other words, unless the method in A is private, the attributes of the method in A and B have to be the same. I guess this does make sense to some extent, in that TMW say "If a method is visible to the subclass, attributes have to be the same; if a method is not visible to the subclass, the subclasses can do whatever they like".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With