What's the best way to prevent a class from being instantiated?
2 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
埃博拉酱
el 23 de Feb. de 2022
Comentada: Steven Lord
el 24 de Feb. de 2022
I want this class to be completely static and can never be instantiated. It only contains a bunch of static methods and constants.
0 comentarios
Respuesta aceptada
Steven Lord
el 23 de Feb. de 2022
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 comentarios
Steven Lord
el 24 de Feb. de 2022
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
Más respuestas (0)
Ver también
Categorías
Más información sobre Loops and Conditional Statements en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!