FalafelPita
FalafelPita

Reputation: 293

Matlab: When implementing methods declared abstract in the super class, why must access be public?

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

Answers (2)

Wolfie
Wolfie

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:

  1. Your super class's method is public and your sub class's method is private
  2. You cannot just set the super class's method to private, or the sub class has no visibility of it.

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:

  • public — Unrestricted access
  • protected — Access from methods in class or subclasses
  • private — Access by class methods only (not from subclasses)

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

Edric
Edric

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

Related Questions