【问题标题】:Matlab: When implementing methods declared abstract in the super class, why must access be public?Matlab:当实现在超类中声明为抽象的方法时,为什么访问必须是公共的?
【发布时间】:2019-02-17 14:01:35
【问题描述】:

在 Matlab (2017a) 中,子类不能限制对在抽象超类中声明为抽象的继承方法的访问。为什么不允许这样做?一个小例子:

超级.m

classdef (Abstract) super
    methods (Abstract)
        out = fun(obj,in)
    end
end

子.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;

执行 testInheritance.m 会导致以下错误消息:

使用子类“sub”中的方法“fun”时出错使用不同的访问权限 权限高于其超类“super”。

【问题讨论】:

    标签: matlab oop inheritance


    【解决方案1】:

    它们不必是公共的,但它们必须可以被子类和超类访问,并且正如错误所述,它们必须相同。所以你有两个问题:

    1. 你的超类的方法是公开的,你的子类的方法是私有的
    2. 您不能只将超类的方法设置为私有,或者子类对其不可见。

    你想设置Access = protected,这意味着只有超类和子类对函数有可见性,因此具有相同的访问权限,可以指定自己的行为,函数对其他对象是隐藏的。

    这里是Access 选项,其定义来自documentation

    • public — 无限制访问
    • protected — 从类或子类中的方法访问
    • private - 只能通过类方法访问(不能从子类

    所以你的课程变成:

    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
    

    请注意,语法是 Access = protected,而不是您显示的 Access = 'protected'

    【讨论】:

    • 谢谢。我没有意识到超类方法是公共的,因为我不认为抽象方法具有任何访问属性。
    【解决方案2】:

    不允许更改在基类中声明为 'public' 的方法的访问属性,使其无法在派生类中访问(这是您的代码试图做的),因为这会违反 @987654321 @。

    换句话说,通过将方法funpublic 更改为private,则客户端不能像使用super 的实例一样使用sub 的实例。

    【讨论】:

      猜你喜欢
      • 2015-02-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多