casparjespersen
casparjespersen

Reputation: 3830

Calling the actual class in Matlab

Let's say I have this class:

classdef abstractGame
    %UNTITLED Summary of this class goes here
    %   Detailed explanation goes here

    properties
    end

    methods (Abstract, Static)
        run(gambledAmount);
    end

    methods (Static)
        function init()
            gambledAmount = validNumberInput(abstractGame.getGambleString(), 1, 100, 'helpText', 'round');
        end
        function str = getGambleString()
            str = 'How much do you want to gamble?';
        end
    end

end

And other classes extends from this class. I would like the child classes to redefine the getGambleString method, and for the init-method to use the one the deepest class defines (instead of abstractGame.[...] I want something like calledClass.[...]).

How should I call that? Thanks in advance.

Upvotes: 1

Views: 338

Answers (1)

Acorbe
Acorbe

Reputation: 8391

That is a static virtual function problem; such a construct, though, doesn't exist even in C++, then I suppose there is no chance to have it in matlab. (virtual function definition.)

Btw, in matlab, non-static methods behave as virtual (as in Java), therefore, if you accept not to use static functions, you can obtain the effect you need.

Proof (simplified code):

classdef abstractGame
  function str = init(obj)
        str = getGambleString(obj);
    end
    function str = getGambleString(obj)
        str = 'How much do you want to gamble?';
    end
  end
end


 classdef game < abstractGame
  methods 

    function str = getGambleString(obj)
        str = 'Hi!';
    end
  end    
 end


d = game;

d.init()

  ans =

   Hi!

Upvotes: 1

Related Questions