问题描述
java中是否有类似静态类
的内容?
Is there anything like static class
in java?
此类的含义是什么?静态类的所有方法都需要 static
吗?
What is the meaning of such a class. Do all the methods of the static class need to be static
too?
是否需要反过来,如果一个类包含所有静态方法,那么该类是否也应该是静态的?
Is it required the other way round, that if a class contains all the static methods, shall the class be static too?
什么是静态类适合的?
推荐答案
Java有静态嵌套类,但听起来你正在寻找一个顶级静态类。 Java无法使顶级类静态,但您可以模拟这样的静态类:
Java has static nested classes but it sounds like you're looking for a top-level static class. Java has no way of making a top-level class static but you can simulate a static class like this:
- 声明您的类
final
- 防止扩展类,因为扩展静态类是没有意义的 - 使构造函数
private
- 防止客户端代码实例化,因为实例化静态类是没有意义的 - 使所有类的成员和函数
static
- 由于无法实例化类,因此无法调用实例方法或访问实例字段 - 请注意,编译器不会阻止您声明实例(非静态)成员。只有在您尝试调用实例成员时才会出现此问题
- Declare your class
final
- Prevents extension of the class since extending a static class makes no sense - Make the constructor
private
- Prevents instantiation by client code as it makes no sense to instantiate a static class - Make all the members and functions of the class
static
- Since the class cannot be instantiated no instance methods can be called or instance fields accessed - Note that the compiler will not prevent you from declaring an instance (non-static) member. The issue will only show up if you attempt to call the instance member
根据上述建议的简单示例:
Simple example per suggestions from above:
public class TestMyStaticClass {
public static void main(String []args){
MyStaticClass.setMyStaticMember(5);
System.out.println("Static value: " + MyStaticClass.getMyStaticMember());
System.out.println("Value squared: " + MyStaticClass.squareMyStaticMember());
// MyStaticClass x = new MyStaticClass(); // results in compile time error
}
}
// A top-level Java class mimicking static class behavior
public final class MyStaticClass {
private MyStaticClass () { // private constructor
myStaticMember = 1;
}
private static int myStaticMember;
public static void setMyStaticMember(int val) {
myStaticMember = val;
}
public static int getMyStaticMember() {
return myStaticMember;
}
public static int squareMyStaticMember() {
return myStaticMember * myStaticMember;
}
}
静态类有什么用?静态类的一个好用途是定义一次性,实用程序和/或库类,其中实例化没有意义。一个很好的例子是Math类,它包含一些数学常量,如PI和E,只是提供数学计算。在这种情况下要求实例化将是不必要和令人困惑的。 。请注意,它是最终的,并且其所有成员都是静态的。如果Java允许将顶级类声明为static,那么Math类确实是静态的。
What good are static classes? A good use of a static class is in defining one-off, utility and/or library classes where instantiation would not make sense. A great example is the Math class that contains some mathematical constants such as PI and E and simply provides mathematical calculations. Requiring instantiation in such a case would be unnecessary and confusing. See Java's Math class. Notice that it is final and all of its members are static. If Java allowed top-level classes to be declared static then the Math class would indeed be static.
这篇关于Java中的静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!