Java 中的静态类 [英] Static Classes In Java
问题描述
java中有没有类似static class
的东西?
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
以上建议的简单示例:
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,并且只提供数学计算.在这种情况下需要实例化将是不必要和混乱的.请参阅数学
类和源代码.请注意,它是 final
并且其所有成员都是 static
.如果 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 the Math
class and source code. 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 中的静态类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!