Matlab subclassing question - oop

Question about subclassing in matlab, under the new class system. I've got class A with some protected properties:
classdef Table < Base
properties (SetAccess = protected, GetAccess = public)
PropA = [];
end %properties
I'd like to make a subclass with some specialized features, and further restrict access to PropA. (i.e. make get access private in the subclass). My first thought was:
classdef subTable < Table
...
methods (Access = private)
out = get.PropA(obj, value);
end %private methods
However, in the help it says: "You must define property access methods in a methods block that specifies no attributes." So much for that idea.
Any ideas?

I don't believe this is possible. From MATLAB Documentation:
There are only two conditions that allow you to redefine superclass properties:
The superclass property Abstract attribute is set to true
The superclass property has both the SetAccess and GetAccess attributes set to private
Nor do I think that doing this would be a good idea. It violates the Liskov Substitution Principle. Functions written to accept a Table should also be able to accept a subTable and work properly. If such a function accessed PropA, it would fail when passed a subTable.

Related

How to read a private attribute of an object without a getter in ABAP

Is there any way to get the value of an objects' private attribute without a getter. Modifying the class is not permitted in any shape or form.
Please find below an example class with a private attribute.
CLASS counter DEFINITION.
PUBLIC SECTION.
METHODS: set IMPORTING value(set_value) TYPE i.
PRIVATE SECTION.
DATA count TYPE i.
ENDCLASS. "counter DEFINITION
CLASS counter IMPLEMENTATION.
METHOD set.
count = set_value.
ENDMETHOD. "set
ENDCLASS. "counter IMPLEMENTATION
How can I get the value of count? Inheriting from counter will not work because count is private, not protected.
Unfortunately not, I have tried this myself in many different ways none of which work:
Having a standard super class - the super class cannot access the
private attributes of subclasses dynamically
Making a subclass will never work since it can only access protected
Attempting to use the unit test framework doesn't work. I tried to
call the kernel modules that allow access to private data but to no
avail.
You are basically flat out of luck. There is one obscure option though depending on the class you are trying to access. Some classes have interfaces specified as friends and if you implement that interface you can access their private data (the ALV on 7.20 is like this) but unfortunately this will only work in a few limited cases.
Runtime type services are the abap's equivalent of reflection.
They allow You nearly to scan every object, and mostly even modify it at runtime. As far as i know, the visibility of attributes does not matter. But be careful.
And read about the various classes, because there are many, each specified to work on a special type of dataopbject ( structs, objects, etc)
http://wiki.scn.sap.com/wiki/pages/viewpage.action?pageId=42965
You could make a sub class, re-implement the setter and set a second variable, then call the parent method. Be aware of the ramifications of having two variables holding the same stuff... Please see vwegert's comments and see if you really want to because it's generally not a great idea and it breaks the rules of OO.
CLASS counter_sub DEFINITION INHERITING FROM counter.
PUBLIC SECTION.
data count2 type i read-only.
METHODS: set REDEFINITION.
ENDCLASS. "counter_sub DEFINITION
CLASS counter_sub IMPLEMENTATION.
METHOD set.
count2 = set_value.
super->set( set_value ).
ENDMETHOD. "set
ENDCLASS. "counter_sub IMPLEMENTATION

Matlab: Class destructor not called during clear?

In Matlab I have a class
classdef myClass
properties
% some properties here...
end
methods ( Access = 'public' )
function obj = myClass()
% constructor...
end
function obj = delete( obj )
% suppose to be destructor...
fprintf(1, 'delete\n');
end
end % public methods
end
What is the default behavior of Matlab when I clear a variable of type myClass?
For example:
>> m = myClass();
>> clear m
I would expect Matlab to call the destructor of m at this stage, but it seems like it doesn't!!
My questions:
How can I force a call to the destructor when clearing a variable?
Is this default behavior of Matlab's makes any sense? Isn't it more logical to call the destructor when clearing a variable?
Is it possible that Matlab's classes do not have a detructor method (that is, there is no default method to be called when the class is destroyed)? Or am I missing something?
Is it possible that only classes derived from handle have a destructor (the delete method)?
Thanks!
EDIT : following Jonas' answer, a brief summary:
Matlab has two types of classes: value classes (the default) and handle classes (derived from handle super class). Value classes tends to provide better performance, however, they do not have a destructor functionality.
handle classes do have a destructor function: delete that is called when the class is destroyed. See this question from more details on handle class destructors.
If one wishes to have a destructor-like functionality for value classes, Jona's answer proposes a method utilizing onCleanup functionality.
Thanks for the good answer and the insightful comments!
Delete is only defined as class destructor for handle classes, not value classes (so the answer to Q4 is "yes", see the previous link to the documentation). Value classes work very much like standard Matlab arrays, in that they're passed by value rather than by reference, and in that many of the internals, such as destructors, are hidden from the user. In exchange, they're usually faster (see for example this SO question).
Consequently, I suggest to use the onCleanup functionality if you want to have a delete method being called (note that delete(m) will not actually delete anything, so you may want to make that a private method).
classdef myTestClass
properties
% some properties here...
end
properties (Hidden)
cleanup
end
methods ( Access = 'public' )
function obj = myTestClass()
% constructor...
obj.cleanup = onCleanup(#()delete(obj));
end
end
methods ( Access = 'private' )
%# I suggest hiding the delete method, since it does not
%# actually delete anything
function obj = delete( obj )
fprintf(1, 'delete\n');
end
end % public methods
end

Overriding superclass methods and access modifiers in MATLAB

Consider the following simple class hierarchy:
A.m
classdef A < handle
methods (Access = protected) %# protected vs. private
function foo(obj)
disp('class A')
end
end
end
B.m
classdef B < A
methods (Access = public)
function foo(obj)
disp('class B')
end
end
end
Class B inherits from class A and is supposed to override the protected foo method as public.
If we try to instantiate the derived class, we get the following error:
>> b=B();
Error using B
Method 'foo' in class 'B' uses different access permissions than its superclass 'A'.
The weird thing is if foo was defined as private method in the superclass A, the code works just fine when we invoke the overridden method:
>> clear classes
>> b=B(); b.foo()
class B
So is this a limitation/bug in MATLAB OOP implementation, or is there a good reason behind this behavior? (Code was tested on R2012b)
As a comparison, in Java the rules state that you cannot reduce visibility of a method in the sub-class, but you can increase it, where:
(weakest) private < package < protected < public (strongest)
This appears to be a limitation of Matlab. I've tried all combinations of attributes. Matlab throws errors whenever the attributes are different, except when the method of A is private, in which case the attributes in B don't matter.
In other words, unless the method in A is private, the attributes of the method in A and B have to be the same. I guess this does make sense to some extent, in that TMW say "If a method is visible to the subclass, attributes have to be the same; if a method is not visible to the subclass, the subclasses can do whatever they like".

Multiple class constructor Matlab

Is it possible define more than one class constructor in Matlab? If yes, how?
Each class has one constructor. However ... the constructor can accept any number and type of arguments, including those based on varargin.
So, to provide the option of a default third argument in Java you could write something like this (examples based on java documentation):
public Bicycle(int startCadence, int startSpeed, int startGear) {
gear = startGear;
cadence = startCadence;
speed = startSpeed;
}
public Bicycle(int startCadence, int startSpeed) {
gear = 1;
cadence = startCadence;
speed = startSpeed;
}
In Matlab you could write
classdef Bicycle < handle
properties (Access=public)
gear
cadence
speed
end
methods (Access = public)
function self = Bicycle(varargin)
if nargin>2
self.gear = varargin{3};
else
self.gear = 1;
end
self.cadence = varargin{1};
self.speed = varargin{2};
end
end
end
The answer of Pursuit works, but a user not familiar to the function can't see how many arguments are needed or what they are for. I would recommend this:
methods (Access = public)
function self = Bicycle(startCadence, startSpeed, startGear)
if nargin>2
self.gear = startGear;
else
self.gear = 1;
end
self.cadence = startCadence;
self.speed = startSpeed;
end
end
If you now type "Bicycle(" and wait you can see at least the three arguments. The second possibility is not shown though. It seems possible (e.g. for plot) but I don't know how to do this.
Each class has only one constructor, and each .m-file can only contain one class definition.
If you want to have a class with slight differences depending on input, you can use properties that define switches that are recognized by the class methods. If you want to have very different classes depending on input, you can create a generateClass-function that will call either one or the other class defined in different files. Of course, if these different classes have lots of common methods and properties, you can create both as subclasses to a common superclass.
No. The constructors in OOP matlab are very restricted compared to other languages. It is not explicitly stated in the documentation AFAIK that you can have multiple constructors, but it refers to the constructor of a class in the singular throughout the documentation.
https://www.mathworks.com/help/matlab/matlab_oop/class-constructor-methods.html

VB.NET - I'm Refactoring and Could Use Some Help

I'm working with vb.net, wcf, wpf and I'm refactoring working code with the hope of being able to reduce some amount of redundancy. I have a bunch of methods that get called in several places throughout the code that only have a slight variation from each other and I would like to replace them with a single method instead.
Specifically, each of the redundant methods process an 1-d array that contain different objects I have created. There are several of these different object types each with different signatures but they have all have a "name" and "Id" property. (Also these objects don't have a shared base class but I could add that if needed.) Each of the redundant methods deal with a different one of the object types.
To refactor the code I would like to pass any of the different object arrays to a single new method that could access the "name" and "id" properties. I'm trying to write this new method in a fashion that wouldn't require me to update it if I created more objects down the road.
I've done some reading on Delegates and Generic Classes but I can't really figure out how this fits in. It would almost be as if I wanted to create a generic class that could handle each of my object types but then somehow also access the "name" and "id" propeties of the different object types.
Any help you can provide would be appretiated. Also, please keep in mind this project is written in VB.net.
Thanks
Mike
It sounds like having your object implement a common interface or have a shared base class would be best. Interfaces give you the most flexibility down the road if you ever need to pass a class to this method that must derive from some other class that does not implement the interface. However, a base class that implements the interface may also be useful just to reduce the duplicate declarations of these properties.
Public Interface IThingThatHasNameAndId 'good name not included
ReadOnly Property Name As String
ReadOnly Property Id As Integer
End Interface
Once you have the interface, you can then pass arrays of types implementing the interface as IEnumerable(Of IThingThatHasNameAndId) or make a generic method taking T() and constrain T to the interface.
Make a base class with the Name and ID properties, then you can make a method that takes in any class that derrives from that class.
Public Function TestFunction(Of t As YourBaseClass)(Byval obj As t) As Boolean
If obj.Name = "Some Name" AndAlso obj.ID = 1 Then
Return True
Else
Return False
End If
End Function