subset enumeration class of an enumeration class

3 views (last 30 days)
I have defined an enumeration class:
classdef globalnumbers<uint8
enumeration
number0 (0)
number1 (1)
number2 (2)
number3 (3)
end
end
Can I create a subset of this globalnumber enumeation? for instance
classdef mynumbers<globalnumbers
enumeration
mynumberA (globalnumbers.number1)
mynumberB (globalnumbers.number2)
end
end
If not, what would be the alternative?
  2 Comments
Sylvain
Sylvain on 10 Apr 2025
I have this error.
'mynumbers' cannot subclass 'globalnumbers' because 'globalnumbers' is an enumeration class.
I think it is not possible.

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 10 Apr 2025
You cannot inherit from an enumeration class as stated on the documentation page listing restrictions on enumerations. They are inherently Sealed. Why?
Suppose you had the class WeekDays (copied from a documentation page):
classdef WeekDays
enumeration
Monday, Tuesday, Wednesday, Thursday, Friday
end
end
and you created a subclass Days.
classdef Days < WeekDays
enumeration
Saturday, Sunday
end
end
Days would have enumeration values Monday, Tuesday, etc. as well. But Days would violate the Liskov substitution principle, as you can't necessarily substitute an instance of Days for an instance of WeekDays and have the program remain correct. Conceptually speaking, suppose I had a program that asked "Is the stock market open?" The stock market is open on days listed in WeekDays but not open on all the days listed in Days. So if that function were something like (not tested, just for illustration purposes)
function tf = isStockMarketOpen(queryDay)
listOfDaysItCouldBeOpen = WeekDays;
tf = ismember(queryDay, listOfDaysItCouldBeOpen);
end
the function could behave differently if I substituted Days for WeekDays. With WeekDays it would return false for Saturday, with Days it would return true.
I believe you can have your class use values from an enumeration class in its definition:
classdef mynumbers
enumeration
mynumberA (globalnumbers.number1)
mynumberB (globalnumbers.number2)
end
end
But now mynumbers is-not-a globalnumbers. So there's no substitutability expectation and so Liskov doesn't apply.

Categories

Find more on Enumerations in Help Center and File Exchange

Products


Release

R2024b

Community Treasure Hunt

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

Start Hunting!