How to define a static class?
The syntax for defining a static class varies depending on the programming language you are using. In C#, you can use the static keyword before the class name, and make sure that all the methods and fields are also marked as static. For example:
static class MathUtils
{
public static double PI = 3.14;
public static double Distance(double x1, double y1, double x2, double y2)
{
return Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
}
}
In Java, you cannot use the static keyword for the class name, but you can make the constructor private, and declare all the methods and fields as static. For example:
class StringUtils
{
private StringUtils() {} // private constructor
public static String ToUpper(String s)
{
return s.toUpperCase();
}
}
In Python, you can use the @staticmethod decorator to mark the methods as static, and define the fields as class variables. For example:
class Logger:
LOG_FILE = "log.txt"
@staticmethod
def Write(message):
with open(Logger.LOG_FILE, "a") as f:
f.write(message + "\n")