Is there more than one way to make a class abstract?
12 views (last 30 days)
Show older comments
In the documentation for abstract classes, the only way I can find to create an abstract class is to define at least one abstract method. Any subclass must then implement the abstract methods. Yet I can create the following class:
classdef nextToNothing < hgsetget
properties
x
end
end
and it works just fine (I can demonstrate almost all the documented behavior of SET, for example, with just this class). Clearly, I don't have to implement any abstract method. Is there another way to make a class abstract?
EDIT: I tried just adding an empty methods block:
methods(Abstract)
end
but that didn't have any effect.
EDIT: You can also define an abstract property, but then the property has to be redefined in subclasses.
0 Comments
Answers (2)
Anshuman
on 20 Aug 2024 at 5:43
If you want to make a class abstract without defining abstract methods or properties, you can use an abstract methods block, but it should not be empty. Instead, you can declare an abstract method without providing its implementation:
classdef nextToNothing < hgsetget
methods(Abstract)
someMethod(obj)
end
end
Here, 'nextToNothing' is abstract because it declares an abstract method someMethod, which must be implemented by any subclass. Simply adding an empty 'methods(Abstract)' block does not make the class abstract. You need to declare at least one abstract method or property.
0 Comments
Steven Lord
on 20 Aug 2024 at 12:50
"A class is abstract when it declares:
- The Abstract class attribute
- An abstract method
- An abstract property
If a subclass of an abstract class does not define concrete implementations for all inherited abstract methods or properties, it is also abstract."
In the case of hgsetget use the metaclass operator ? to confirm it is abstract and matlab.metadata.abstractDetails to determine which abstract methods or properties it defines (if any.)
metadata = ?hgsetget;
metadata.Abstract % true means it is abstract
matlab.metadata.abstractDetails('hgsetget')
The fact that this says hgsetget has no abstract methods or properties indicates to me that its implementation makes it abstract by setting the Abstract class attribute. Since the original question's subclass of hgsetget has no abstract methods or properties (it didn't inherit any from hgsetget) and doesn't set the Abstract class attribute, it's not abstract.
0 Comments
See Also
Categories
Find more on Construct and Work with Object Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!