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

3 ビュー (過去 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 Center および File ExchangeLoops 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