java中可以写静态类,Java中的静态类

Java不支持顶级静态类,但可以通过使类final并仅包含静态成员来模拟静态类。这种类通常用于一次性、工具类或库,例如Java的Math类。静态类防止实例化,所有方法和成员必须为静态,不适用于需要实例状态的情况。
摘要由CSDN通过智能技术生成

Is there anything like static class in java?

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?

What are static classes good for?

解决方案

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:

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;

}

}

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值