Why does MATLAB attempt to instantiate abstract properties? - matlab

There is unexpected (to me) behavior when combining class property validation with abstract properties in MATLAB. Here is a short example involving three classes:
classdef TestClass
properties (Abstract)
aprop (1,1) TestClassB
end
end
classdef TestClassB
methods
function obj = TestClassB(a)
disp(a);
end
end
end
classdef TestClassC < TestClass
properties
aprop
end
end
Then, when attempting to instantiate a TestClassC object, I get the following error:
>> TestClassC()
Error defining property 'aprop' of class 'TestClass'. Unable to construct default
object of class TestClassB.
Evidently, MATLAB is trying to instantiate the abstract property aprop in TestClass and then fails due to the lack of a valid zero-argument constructor in aprop's class definition TestClassB. I realize that the zero-argument constructor issue is in theory fixable (although only if you have access to modify TestClassB), but the fact that MATLAB is instantiating an abstract property at all seems very strange. The first line of the Wikipedia article on abstract types literally states:
...an abstract type is a type in a nominative type system that cannot be instantiated directly...
Perhaps this is the only way that MATLAB, as a weakly typed language, can implement property validation, but this is an unfortunate result.
On a side note, if TestClassB has a valid zero-argument constructor but is defined to be abstract, you end up falling into the same trap but with a slightly different error:
>> TestClassC()
Error defining property 'aprop' of class 'TestClass'. Class TestClassB is abstract.
Specify a default value for property aprop.
Is there a good reason for this behavior?
Edit:
Additional test-class observations
Removing the size validation in TestClass eliminates the error. Evidently, MATLAB has no problem initializing a empty array of objects without a valid zero-argument constructor. Note: this only works when TestClassB is not abstract.
If TestClassB is abstract and TestClassC initializes aprop in the property block with a concrete subclass of TestClassB, there is no error (assuming that the concrete subclass has a valid zero-argument constructor). Note: this is not true if aprop is instead initialized in TestClassC's constructor.
Motivating example
The above UML diagram is a typical example of combining inheritance with composition. GenericCar and GenericEngine are abstract classes. GenericCar contains a GenericEngine, but Racecar specifies its engine as a concrete V8 (which "isa" GenericEngine). Unfortunately, this can't be constructed using property validation in MATLAB since MATLAB will not allow you to re-define the class of an abstract property even if it is a subclass of the original definition.
Suppose you accept that you can't define engine in Racecar as a V8. Even so, if you don't supply an initial value for engine in the property block of Racecar, MATLAB will throw an error when creating a Racecar object since it will try to initialize engine using the abstract type GenericEngine. This is true even if the constructor of Racecar initializes engine as a V8 object. This highlights the odd connection between property validation and object instantiation.

It seems that two questions should be answered:
1 - "Evidently, MATLAB is trying to instantiate the abstract property aprop in TestClass. So why does MATLAB attempt to instantiate abstract properties?"
According to the documentation (emphasis is by me):
You can define property validation for abstract properties. The validation applies to all subclasses that implement the property.
MATLAB is trying to instantiate the property aprop in TestClassC that is a concrete subclass of TestClass. But it uses the same validation rules that is used in TestClass. The aprop property of TestClassC isn't abstract.
2 - "If TestClassB ... is defined to be abstract, you end up falling into the same trap..."
Referring to the documentation:
abstract class — A class that cannot be instantiated, but that defines class components used by subclasses.
TestClassC uses the same validation rules that is used in TestClass. It tries to instantiate its aprop member that is of class TestClassB but TestClassB is abstract and cannot be instantiated.

Related

Invoking method of a class as another class' attribute in Matlab

Apologize if the title is confusing.
I tried to set an attribute of a class as another class:
classdef gun
properties
bullets;
...
Where bullets is later initialized as another class object bullets = bul(10);
classdef bul
properties
...
methods
function obj = addBullet(obj, num)
...
But when I tried to invoke method addBullet in class gun, like gun.bullets.addBullet(2), I got an error saying:
Dot indexing is not supported for variables of this type.
Is it because Matlab does not support class as another class' attribute? Any way I can fix that?

In Racket's class system, what do augment, overment, augride, etc. do?

Racket's documentation only partially describe what augment and pubment do: augment makes a method that executes after the superclass's version of that method, while pubment makes a method that will implicitly have the augment property if it is defined in a child class.
The docs say absolutely nothing about overment and augride, and I can't guess what they would do based on their names. What are they, and what is the difference between them?
The relatively large family of inheritance functions for Racket's class system is, as you describe, a little confusing, and their somewhat cutesy names don't always help.
In order to understand this, Racket provides two separate mechanisms for method inheritance.
public methods correspond to the classical idea of public methods in other OO models. Methods declared with public may be overridden in subclasses, unless they're declared final, in which case they cannot.
pubment methods are similar, but they cannot be overridden, only augmented. Augmenting a method is similar to overriding it, but the dispatch calls the superclass's implementation instead of the subclass's.
To clarify the difference between overriding and augmentation, when an overridden method is called, the overriding implementation is executed, which may optionally call the superclass's implementation via inherit/super. In contrast, in an augmented method, the superclass's implementation receives control, and it may optionally call the subclass's implementation via inner.
Now, we're also provided public-final, override-final, and augment-final. These are pretty simple. Declaring a method with public-final means it can neither be augmented nor overridden. Using override-final overrides a superclass's public method, but it doesn't allow any further overriding. Finally, augment-final is similar, but for methods declared with pubment, not public.
So then, what about the two weird hybrids, overment and augride?
overment can be used to implement methods initially defined with public. This "converts" them to augmentable methods instead of overridable methods for all the class's subclasses.
augride goes in the opposite direction. It converts an augmentable method to one that is overridable, but the overriding implementations only replace the augmentation, not the original implementation.
To summarize:
public, pubment, and public-final all declare methods that do not exist in a superclass.
Then we have a family of forms for extending superclass methods:
override and augment extend methods declared with public and pubment, respectively, using the relevant behaviors.
override-final and augment-final do the same as their non-final counterparts, but prevent further overriding or augmentation.
overment and augride convert overridable methods to augmentable ones and vice-versa.
For another, fuller explanation, you might be interested in taking a look at the paper from which Racket's model was derived, which is quite readable and includes some helpful diagrams.

What is purpose of abstract property in MATLAB?

We have the abstract attribute of methods and properties in MATLAB R2014b, and I know the purpose of abstract attribute for methods. We can call functions in that method and define it in the superclass of a class. What I'm confused about is the purpose of the abstract attribute for a property in MATLAB. How do we use this?
The purpose of abstract properties (and abstract methods) is to allow the creation of interfaces:
The basic idea of an interface class is to specify the properties and methods that each subclass must implement without defining the actual implementation.
For example, you can define an abstract Car with the definition
classdef (Abstract) Car
properties(Abstract) % Initialization is not allowed
model
manufacturer
end
end
The abstract properties model and manufacturer cannot be initialized (that would be like instantiating an abstract class) and all classes that inherit from Car must specify their value for the subclass to be concrete.
If the properties were not abstract, the subclass would simply inherit them.
Making the properties abstract forms a contract of sorts that says "for you to be a usable (concrete) car you must have a model and manufacturer defined".
Therefore, in the definition
classdef FirstEveryManCar < Car
properties
model = 'T';
manufacturer = 'Ford';
end
end
the property definitions are compulsory for the class to not be made abstract automatically (which you could do if you have long class hierarchies).
There is a significant consequence for setter/getter methods (i.e. set.Property & get.Property).
Due to the way Matlab works, you can only implement setter/getter methods inside the class definition file of the class that declares the property. Therefore if you want to ensure a property is defined in the interface, but require implementation specific setter/getter methods, then declaring the property Abstract in the interface class ensures the subclass redefines the property and enables that class to define its own setter/getter methods.
Example 1 (Does not work)
Superclass
classdef (Abstract) TestClass1 < handle
properties
Prop
end
end
Subclass
classdef TestClass2 < TestClass1
methods
function obj = TestClass2(PropVal)
if nargin>0
obj.Prop = PropVal;
end
end
function set.Prop(obj, val)
if ~isnumeric(val)
error('Not a number!');
end
obj.Prop = val;
end
end
end
Example 2 (The correct way)
Superclass
classdef (Abstract) TestClass1 < handle
properties (Abstract)
Prop
end
end
Subclass
classdef TestClass2 < TestClass1
properties
Prop
end
methods
function obj = TestClass2(PropVal)
if nargin>0
obj.Prop = PropVal;
end
end
function set.Prop(obj, val)
if ~isnumeric(val)
error('Not a number!');
end
obj.Prop = val;
end
end
end
I don't know any example where you really need it, but it is typically used when a abstract superclass uses properties without having a reasonable default. This is a extremely trimmed down example, but imagine welcome implementing a full user interface while welcomeGer fills all required properties to provide it in german language:
%welcome.m
classdef welcome
properties(Abstract)
text
end
methods
function printText(obj)
disp(obj.text)
end
end
end
%welcomeGer.m
classdef welcomeGer<welcome
properties
text='Willkommen in unserem Hotel'
end
end
Alternative you could skip the definition of text at all, but then matlab would not throw an error when you forget to initialize text

Error when inheriting from Ektron.Cms.Content.Targeting.Rules.RuleTemplate

I have a C# class called MyCustomRuleTemplate which is inherited from Ektron.Cms.Content.Targeting.Rules.RuleTemplate class. In that I have added a constructor such as below
public MyCustomRuleTemplate(): base("someKey")
{
//Some code here
}
Its working fine without any error. If I given it as
public MyCustomRuleTemplate()
{
//Some code here
}
Im getting error like 'Ektron.Cms.Content.Targeting.Rules.RuleTemplate' does not contain a constructor that takes 0 arguments.
Can anybody help me to know why it is?
The reason you are seeing "does not contain a constructor that takes 0 arguments" when instantiating your class object using the second constructor is because when you call your constructor, c# tries to call the constructor on the base class as well, which in this case takes a parameter.
See this post on msdn:
http://msdn.microsoft.com/en-us/library/ms173115%28v=vs.80%29.aspx
Key parts:
"In this example, the constructor for the base class is called before the block for the constructor is executed. The base keyword can be used with or without parameters. Any parameters to the constructor can be used as parameters to base, or as part of an expression. For more information, see base.
In a derived class, if a base-class constructor is not called explicitly using the base keyword, then the default constructor, if there is one, is called implicitly."
And: "If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor using base."

Scala: invoking superclass constructor

I am experiencing a weird behavior by Scala handling of superclass constructors.
I have a really simple class defined in the following way
package server
class Content(identifier:String,content:String){
def getIdentifier() : String = {identifier}
def getContent() : String = {content}
}
and a simple subclass
package server
class SubContent(identifier:String, content:String) extends Content(identifier, content+"XXX")){
override def getContent():String = {
println(content)
super.getContent
}
}
What's really strange is that in the subclass there are duplicates of the superclass attributes, so if i create a new object
var c = new SubContent("x","x")
the execution of
c.getContent
first prints out "x" (The valued provided to the subclass constructor), but returns "xXXX" (The value provided to the superclass constructor).
Is there any way to avoid this behavior? Basically what I'd like to have is that the subclass does not create its own attributes but rather just passes the parameters to the superclass.
It's doing exactly what you told it to do. You augmented the 2nd constructor parameter when passing it on to the superclass constructor and then you used the superclass' getContent to provide the value returned from the subclass' getContent.
The thing you need to be aware of is that constructor parameters (those not tied to properties because they're part of a case class or because they were declared with the val keyword) are in scope throughout the class body. The class' constructor is that part of its body that is outside any method. So references to constructor parameters in method bodies forces the constructor parameter to be stored in a field so it can have the necessary extent. Note that your println call in getContent is causing such a hidden constructor parameter field in this case.
Replying to comment "Is there an alternative way to define it in order to avoid this? Or at least, if I never refer to the parameters of the subclass constructors their fields will be allocated (Wasting memory)?":
If the only references to plain constructor parameters (*) is in the constructor proper (i.e., outside any method body, and val and var initializers don't qualify as method bodies) then no invisible field will be created to hold the constructor parameter.
However, If there's more you're trying to "avoid" than these invisible fields, I don't understand what you're asking.
(*) By "plain constructor parameters" I mean those not part of a case class and not bearing the val keyword.