1

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.

casparjespersen
  • 3,460
  • 5
  • 38
  • 63

1 Answers1

1

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!
Community
  • 1
  • 1
Acorbe
  • 8,367
  • 5
  • 37
  • 66
  • Actually, I think you could do quasi-virtual statics using Matlab's dynamic method dispatch. `eval([class(obj) '.getGambleString'])` will invoke the static getGambleString method on the particular class of the object, at the expense of requiring you to redefine the method in every subclass, and slow invocation. Not that I'm recommending one actually do this. Your non-static solution is better in practice IMO. – Andrew Janke Nov 23 '12 at 02:32