Java 中 C 的“静态”关键字的等价物是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/728534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 13:32:01  来源:igfitidea点击:

What's the equivalent of C's "static" keyword in Java?

javacstatic

提问by AGeek

I want to know what could be the equivalent keyword in java which could perform same function as "Static keyword in C".. I want to do recursion in java, performing same function that a static keyword in C does...

我想知道什么可能是 java 中的等效关键字,它可以执行与“C 中的静态关键字”相同的功能..我想在 Java 中进行递归,执行与 C 中的静态关键字相同的功能......

Please help..

请帮忙..

回答by Adam Rosenfield

C has two entirely different uses of the statickeyword, and C++ adds a third use:

C 有两种完全不同的static关键字用法,C++ 增加了第三种用法:

// Use 1: declare a variable or function to be local to a given module
// At global scope:
static int global_var;
static void func();

In this case, the global variable global_varand the function void func()can only be accessed inside the file in which they are declared; they cannot be accessed by any other file.

在这种情况下,全局变量global_var和函数void func()只能在声明它们的文件内访问;它们不能被任何其他文件访问。

// Use 2: declare a variable inside a function with global scope
void func(void)
{
    static int x;
}

In this case, the variable xis effectively a global variable, in that there is only one instance of it -- multiple calls to func()(including recursive calls) will always access the same variable.

在这种情况下,变量x实际上是一个全局变量,因为它只有一个实例——多次调用func()(包括递归调用)将始终访问同一个变量。

// Use 3 (C++ only): declare a global variable with class scope
class Widget
{
public:
    static int var;
};

In this case, this declares the variable Widget::varas a global variable, but its scope is different. Outside of class member functions, it has to be named as Widget::var; inside class member functions, it can be named as just var. It can also be made protectedor privateto limit its scope even more.

在本例中,this 将变量声明Widget::var为全局变量,但其作用域不同。在类成员函数之外,它必须命名为Widget::var; 在类成员函数中,它可以命名为 just var。它也可以被制造protectedprivate进一步限制其范围。

Now, what are the analogs of these 3 uses in Java?

现在,Java 中这 3 种用法的类似物是什么?

Case 1 has no direct analog; the closest is declaring objects with package scope, which is done by omitting a public, protected, or private:

情况 1 没有直接模拟;最接近的是声明具有包范围的对象,这是通过省略 a public, protected, or 来完成的private

class Widget  // Declare a class with package scope
{
    int x;  // Declare a member variable with package scope
    void func() {}  // Declare a member function with package scope
}

In this case, the declared objects are only accessible by classes within the same package; they are not accessible to other packages.

在这种情况下,声明的对象只能被同一包内的类访问;其他软件包无法访问它们。

Case 2 also does not have an analog in Java. The closest you can get is by declaring a global variable (that is, a static class variable, since Java doesn't have true global variables in the strictest sense):

情况 2 在 Java 中也没有类似物。最接近的方法是声明一个全局变量(即静态类变量,因为 Java 在最严格的意义上没有真正的全局变量):

class Widget
{
    private static int func_x;
    public static void func()
    {
        // use func_x here in place of 'static int x' in the C example
    }
}

Case 3 is the only case that has a directanalog in Java. In this case, the statickeyword serves exactly the same purpose.

案例 3 是唯一一个在 Java 中直接类似的案例。在这种情况下,static关键字的作用完全相同。

回答by paxdiablo

The "static"keyword in C actually serves two functions depending on where it's used. Those functions are visibility and duration (these are my terms based on quite a bit of teaching, the standard, if you're interested in that level of detail, uses different terms which I often find confuses new students, hence my reticence in using them).

"static"C 中的关键字实际上有两个功能,具体取决于它的使用位置。这些功能是可见性和持续时间(这些是我基于大量教学的术语,如果您对该级别的细节感兴趣,标准会使用不同的术语,我经常发现这些术语会使新学生感到困惑,因此我对使用它们保持沉默)。

  • When used at file level, it marks an item (variable or function) as non-exported so that a linker cannot see it. This is static as in visibility, duration is the same as the program (i.e., until the program exits). This is useful for encapsulating the item within a single compilation unit (a source file, in its simplest definition). The item is available to the whole compilation unit (assuming it's declared before use).
  • When used within a function, it controls duration (visibility is limited to within the function). In this case, the item is also created once and endures until the program exits. Non-static variables within a function are created and destroyed on function entry and exit.
  • 在文件级别使用时,它将项目(变量或函数)标记为未导出,以便链接器无法看到它。这是静态的,因为可见性,持续时间与程序相同(即,直到程序退出)。这对于将项目封装在单个编译单元(源文件,最简单的定义)中很有用。该项目可用于整个编译单元(假设它在使用前已声明)。
  • 在函数内使用时,它控制持续时间(可见性仅限于函数内)。在这种情况下,项目也被创建一次并持续到程序退出。函数内的非静态变量在函数进入和退出时创建和销毁。

I gather what you're after is the first type, basically a global variable since I can't immediately see much of a use for the other variant in recursion..

我收集到你所追求的是第一种类型,基本上是一个全局变量,因为我无法立即看到递归中其他变体的很多用途..

It can't be done since, in Java, everythingmust belong to a class. The workaround is to create a class holding the "globals" and either:

这是不可能的,因为在 Java 中,一切都必须属于一个类。解决方法是创建一个包含“全局变量”的类,并且:

  • pass that object around so you can reference its members; or
  • construct a singleton item so you can access its members.
  • 传递该对象,以便您可以引用其成员;或者
  • 构造一个单例项,以便您可以访问其成员。

回答by John Feminella

Java doesn't have global variables, so there isn't a direct equivalent. However, there's a statickeyword in Java that shares the state of a field with all instances of a class, which is a good approximation to what you're describing.

Java 没有全局变量,所以没有直接的等价物。但是,staticJava 中有一个关键字与类的所有实例共享字段的状态,这与您所描述的情况非常接近。

I want to do recursion in java, performing same function that a static keyword in C does...

我想在 Java 中进行递归,执行与 C 中的静态关键字相同的功能......

However, if you're looking to do recursion, are you sure that static variables are what you need?Any special state needed for a recursive function call is almost always passed back to itself, not maintained separately.

但是,如果您要进行递归,您确定静态变量是您所需要的吗?递归函数调用所需的任何特殊状态几乎总是传递回自身,而不是单独维护。

回答by Adeel Ansari

The concept of staticin Java doesn't adhere with the concept of staticin C. However, there is a statickeyword in Java as well. But its more like a staticin C++ then C, with some differences.

概念静态在Java中没有与理念坚持静态的。然而,有一个静态Java中的关键字为好。但它更像是C++ 中的静态,然后是 C,有一些差异。

回答by Gerard

You can simulate a static class in java as follows:

你可以在java中模拟一个静态类,如下所示:

   /**
     * Utility class: this class contains only static methods and behaves as a static class.
     */

public abstract class Utilities
    {
        // prevent inheritance
        private Utilities()
        {
        }
    // ... all your static methods here
        public static Person convert(string) {...}
    }

This class cannot be inherited (like final because although abstract it has a private constuctor), cannot be instantiated (like static because abstract) so only static methods in it can be called.

这个类不能被继承(像 final 因为虽然抽象它有一个私有构造函数),不能被实例化(像静态因为抽象)所以只能调用其中的静态方法。