Let we have one abstract class:
classdef ACalculation < handle
methods (Abstract)
[result] = calculate (this, data);
plot (this, data, limX, limY);
end
end
And some other classes that implements ACalculation
classdef Maximum < ACalculation
methods
function [result] = calculate (this, data)
%...
end
function plot (this, data, limX, limY)
%...
end
end
To functions of implementation class i give all needed information, so i don't need any properties. So it looks like I need static classes. But if I have static classes I have a problem with calling this functions. I'd like to do something like that:
criteria = Maximum();
%......
result = criteria.calculate(data);
Is it bad way to use inheritance? Should I ignore matlab advices to change functions to static? What else could I do here?
An abstract class cannot be instantiated. An abstract class not only contains abstract methods and assessors but also contains non-abstract methods, properties, and indexers.
Yes, we can declare an abstract class with no abstract methods in Java. An abstract class means that hiding the implementation and showing the function definition to the user.
Generally, we use abstract class at the time of inheritance. A user must use the override keyword before the method is declared as abstract in the child class, the abstract class is used to inherit in the child class. An abstract class cannot be inherited by structures.
Abstract classes are similar to interfaces. You cannot instantiate them, and they may contain a mix of methods declared with or without an implementation. However, with abstract classes, you can declare fields that are not static and final, and define public, protected, and private concrete methods.
I think that in this case, static interface implementation is quite a good pattern. Define your classes in the following way:
classdef ACalculation < handle
methods (Abstract,Public,Static)
[result] = calculate (data);
plot (data, limX, limY);
end
end
classdef Maximum < ACalculation
methods (Public,Static)
function [result] = calculate (data)
%...
end
function plot (data, limX, limY)
%...
end
end
Then, you can write a function that expects an ACalculation
type:
function foo(acalc,data)
assert(isa(acalc,'ACalculation'));
acalc.calculate(data);
acalc.plot(data,[100 200]);
end
Then create a Maximum
empty instance and pass it to foo
:
foo ( Maximum.empty(0), [1 2 3]);
If you want to change the calculation method, call
foo ( Minimum.empty(0), [1 2 3]);
When you say that such a pattern will not work, you are thinking like Java/C#/C++ developer. But unlike in C++ where static and virtual keyword cannot coexist, Matlab has no such limitation, because everything is done at runtime, and an "instance" can be empty or an array of n
elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With