Is there more than one way to make a class abstract?

4 vues (au cours des 30 derniers jours)
Andrew Newell
Andrew Newell le 28 Fév 2011
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.

Réponses (2)

Anshuman
Anshuman le 20 Août 2024
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.

Steven Lord
Steven Lord le 20 Août 2024
As stated on this documentation page, there are several ways to make a class abstract.
"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
ans = logical
1
matlab.metadata.abstractDetails('hgsetget')
No abstract methods or properties for class hgsetget or no class 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.

Catégories

En savoir plus sur Create System Objects dans Help Center et File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by