subset enumeration class of an enumeration class

조회 수: 3 (최근 30일)
Sylvain
Sylvain 2025년 4월 10일
답변: Steven Lord 2025년 4월 10일
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
Matt J
Matt J 2025년 4월 10일
Sure, why not?
Sylvain
Sylvain 2025년 4월 10일
I have this error.
'mynumbers' cannot subclass 'globalnumbers' because 'globalnumbers' is an enumeration class.
I think it is not possible.

댓글을 달려면 로그인하십시오.

답변 (1개)

Steven Lord
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.

카테고리

Help CenterFile Exchange에서 Enumerations에 대해 자세히 알아보기

제품


릴리스

R2024b

Community Treasure Hunt

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

Start Hunting!

Translated by