Dormire
Dormire

Reputation: 123

Why do I have to call the constructor of the superclass when defining that of the subclass?

I have been struggling with the following problem. Let's say we have a superclass super, which is itself handle class, and a subclass sub of super. The following program doesn't work:

super.m

classdef super < handle
    properties
        x
    end

    methods
        function this = super(value)
            this.x = value;
        end
    end
end

sub.m

classdef sub < super
    methods
        function this = sub(value)
             this.x = 2*value;
        end
    end
end

If I run sub(1), it prompts that

Not enough input arguments.

Error in super (line 8)
            this.x = value;

Error in sub

However, if I simply change this.x = 2*value to this = this@super(2*value) in sub.m, it works perfectly fine now...

From time to time I will have to initialize some properties in the subclass inherited from a superclass in a different way, and that's why I am confused. Must I call the constructor of the superclass in this case?

Any help will be greatly appreciated!

Upvotes: 2

Views: 112

Answers (1)

sco1
sco1

Reputation: 12214

This is explicit in the documentation:

If you do not explicitly call the superclass constructors from the subclass constructor, MATLAB® implicitly calls these constructors with no arguments. In this case, the superclass constructors must support no argument syntax.

The functional super.m:

classdef super < handle
    properties
        x
    end

    methods
        function this = super(value)
            if nargin ~= 0
                this.x = value;
            end
        end
    end
end

Upvotes: 2

Related Questions