필터 지우기
필터 지우기

What's the best way to prevent a class from being instantiated?

조회 수: 1 (최근 30일)
埃博拉酱
埃博拉酱 2022년 2월 23일
댓글: Steven Lord 2022년 2월 24일
I want this class to be completely static and can never be instantiated. It only contains a bunch of static methods and constants.

채택된 답변

Steven Lord
Steven Lord 2022년 2월 23일
Make it Abstract.
classdef (Abstract) purelyStatic
methods(Static)
function y = getPi()
y = pi;
end
end
properties(Constant)
theAnswerToLifeTheUniverseAndEverything = 42;
end
end
Use it as:
P = purelyStatic.getPi()
A = purelyStatic.theAnswerToLifeTheUniverseAndEverything
Trying to instantiate it will error.
x = purelyStatic
  댓글 수: 2
埃博拉酱
埃博拉酱 2022년 2월 24일
It's just abstract. It can be inherited and then instantiated.
Steven Lord
Steven Lord 2022년 2월 24일
Make it Sealed as well. That still wouldn't prevent someone from editing the class file but there isn't really a way to make it so it can never, ever, ever be modified. At least not while butterflies exist :)
classdef (Abstract, Sealed) purelyStatic

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품


릴리스

R2021b

Community Treasure Hunt

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

Start Hunting!

Translated by