george andrew
george andrew

Reputation: 471

Is there any workaround to call a superclass method in a subclass method with a different name?

I have a superclass defines several methods, and in the derived subclass class, (a) I want to keep these methods since they are still very useful, but I want to give them another name since (b) for the method with the same name as in the superclass, I want to give them a different function.

classdef sup
    methods
        function [] = method1(obj,val)
            fprintf('sup val=%g\n',val);
        end
    end
end

classdef sub < sup
    methods
        function [] = method1(obj,val)
            fprintf('sub val=%g\n',val);
        end
        function [] = method2(obj,val)
            method1@sup(obj,val);
        end        
        
    end
end

This is not allowed by matlab. But this looks very natural to me to call the methods with the same name for superclass and subclass resulting different results, meanwhile still want the methods in superclass alive in case I need. Is there any workaround or there is a better OOP concept to avoid this?

Upvotes: 1

Views: 370

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60443

If you want to be able to call method1@sup with an object of class sub, you shouldn’t override the method1 function. If you override a function, you are saying that the base classes’ function is not suitable for this class and needs to work differently.

You might want to just write a function with a different name.

One way to do so is to put the implementation of sup.method1 in a protected function, which you can then call from both sup.method1 and sub.method2:

classdef sup
    methods
        function method1(obj,val)
            method1_impl(obj,val);
        end
    end
    methods(Access=protected)
        function method1_impl(obj,val)
            fprintf('sup val=%g\n',val);
        end
    end
end

classdef sub < sup
    methods
        function method1(obj,val)
            fprintf('sub val=%g\n',val);
        end
        function method2(obj,val)
            method1_impl(obj,val);
        end
    end
end

Upvotes: 3

Related Questions