subset enumeration class of an enumeration class
조회 수: 3 (최근 30일)
이전 댓글 표시
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?
답변 (1개)
Steven Lord
2025년 4월 10일
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.
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Enumerations에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!