简体   繁体   English

他们在Java中是否具有相当于C#的静态类?

[英]Do they have the equivalent of C# static classes in Java?

Do they have the equivalent of C# static classes in Java? 他们在Java中是否具有相当于C#的静态类?

I want to create a C# static class but in Java, how do I do it? 我想创建一个C#静态类,但在Java中,我该怎么做?

Thanks for the help. 谢谢您的帮助。

EDIT: Thanks for the help guys. 编辑:谢谢你的帮助。 :) :)

There are static members in Java classes, but no static class, like in C#. Java类中有静态成员,但没有静态类,如C#中。

The C# static class modifier doesn't really change anything about the class, from a usage standpoint, though. 但是,从使用的角度来看,C#static class修饰符并没有真正改变关于类的任何内容。 It just prevents you, at compile time, from adding instance variables. 它只会阻止您在编译时添加实例变量。

You can make a class in Java that would work like a C# static class by just declaring every member as static. 您可以通过将每个成员声明为静态来创建一个类似于C#静态类的Java类。 See the tutorial section on " Understanding Instance and Class Members " for details. 有关详细信息,请参阅“ 了解实例和类成员 ”的教程部分。

No. Just mark everything static. 不,只需将一切标记为静态 Possibly add a private constructor that throws an error and make the class final . 可能会添加一个私有构造函数,它会抛出错误并使类成为final

Try this: 试试这个:

public class Util
{
    // final prevents inheritance, just like C# static classes can't be inherited
    // final is basically like the C# sealed keyword.
    public static final class Math
    {
        // prevent constructor from being called
        private Math(){}
        static
        {
            // Acts like a C# static constructor. (only runs once, )
        }
        public static int Add(int num1, int num2)
        {
            return num1+num2;
        }
    }
}

In every OO language,a good (an more flexible) alternative to static class declaration is to use the singleton pattern. 在每种OO语言中,静态类声明的一个好的(更灵活的)替代方法是使用单例模式。

However, if your class is a pure utility class, you can declare all your members/methods as static. 但是,如果您的类是纯实用程序类,则可以将所有成员/方法声明为静态。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM