java中的静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2392028/
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-08-13 06:54:57  来源:igfitidea点击:

Static method in java

javastatic

提问by sandhya

I heard that static methods should use only static variables in java. But, main method is also static, right?

我听说静态方法应该只在 java 中使用静态变量。但是,main 方法也是静态的,对吧?

采纳答案by Mihir Mathuria

Your question: is the statement " static methods should use only static variables" correct?

您的问题:“静态方法应仅使用静态变量”的说法正确吗?

No. The statement is not correct.

不,该陈述不正确。

The correct statement will be "static methods can only use those instance variables that are defined static"

正确的说法是“静态方法只能使用那些定义为静态的实例变量”

Take a look at following code and read the comments:

看看下面的代码并阅读评论:

Class A{
    int i;
    static int j;

    public static void methodA(){
        i = 5; //cannot use since i is not static
        j = 2; //can use.

        int k = 3; //k is local variable and can be used no problem

        **EDIT:**//if you want to access i
        A a = new A();
        //A.i = 5; //can use.  
        a.i = 5; // it should be non-capital "a" right?
    }
}

回答by Steve

A static method is called on a class instance and not to an object of a class. This means, that a static method is not able to access instance variables, because they are only instantiated in an object.

静态方法是在类实例上调用的,而不是在类的对象上调用。这意味着,静态方法无法访问实例变量,因为它们仅在对象中实例化。

If you want to access an instance variable with a static method, you have to declare that variable as static.

如果要使用静态方法访问实例变量,则必须将该变量声明为静态。

public class Test {
    private static int value = 0;

    public static void main(String[] args) {
        value++;
    }
}

But to be honest, it's not the best idea to write everything in static methods. It's better to use the main method to instantiate new objects.

但老实说,用静态方法编写所有内容并不是最好的主意。最好使用 main 方法来实例化新对象。

回答by fastcodejava

Yes static method cannot call non-static methods or variables of the class directly.

是的静态方法不能直接调用类的非静态方法或变量。

EDIT: One can create any local variables.

编辑:可以创建任何局部变量。

回答by polygenelubricants

First of all, a technicality: it's NOTtrue that "mainmethod is also static". You can define a non-static mainmethod, with whatever signature you choose; it just won't be a valid Java application entry point.

首先,一个技术问题:“方法也是静态的”是正确的main。您可以main使用您选择的任何签名定义一个非静态方法;它不会是一个有效的 Java 应用程序入口点。

With regards to "static methods should use only static variables", this is also NOTtrue. The key concept here is that static methods and fields are class-specific, not instance-specific. You simply can't access an instance variable/method if you don't actually have an instance of that class; it's a compilation error.

至于“静态方法应该只使用静态变量”,这也是正确的。这里的关键概念是静态方法和字段是特定于类的,而不是特定于实例的。如果您实际上没有该类的实例,则您根本无法访问该实例变量/方法;这是一个编译错误。

So to be precise, without an instance, you can't access instance fields/methods. You can access static fields/methods without an instance. If you need to access instance fields/methods from a static method, you have to get an instance of that class one way or another, either by simply instantiating it, or by getting a reference to it from a static field or method parameter.

所以准确地说,没有实例,你就不能访问实例字段/方法。您可以在没有实例的情况下访问静态字段/方法。如果您需要从静态方法访问实例字段/方法,您必须以一种或另一种方式获取该类的实例,或者通过简单地实例化它,或者通过从静态字段或方法参数获取对它的引用。

Let's take a look at this simple example:

让我们看一下这个简单的例子:

public static void main(String args[]) {
  System.out.println(args.length);
}

lengthis NOTa static field; it's an instance field of array instances, which argsis. The static method mainis able to get this instance (and thus access its instance methods and fields) because it's passed in as an argument.

length不是一个静态字段; 它是数组实例的实例字段,即args。静态方法main能够获取此实例(从而访问其实例方法和字段),因为它是作为参数传入的。

Also, printlnis NOTa static method; it's an instance method of PrintStreaminstances. The static method mainis able to get this instance by accessing the static field outof the class System.

此外,printlnNOT一个静态方法; 它是实例的实例方法PrintStream。静态方法main能够通过访问静态字段得到这个实例out的类System



To summarize:

总结一下:

  • A Java application entry point is a method that:
    • is named main
    • is publicand static
    • returns voidand takes a String[]argument as parameter
  • A method named maindoesn't have to be a Java application entry point
    • (but it's best to reserve this name for that purpose)
  • Java 应用程序入口点是一种方法:
    • 被命名 main
    • publicstatic
    • 返回void并接受一个String[]参数作为参数
  • 命名的方法main不必是 Java 应用程序入口点
    • (但最好为此目的保留此名称)

Furthermore,

此外,

  • Instance fields/methods can only be accessed through an instance
  • Static fields/methods can be accessed without an instance
  • Static methods can get an instance of a class by one of the following ways:
    • creating a newinstance
    • having it passed as an argument
    • accessing it through a staticfield of a class
    • accepting it as the return value of a staticmethod of a class
    • catching it as a thrown Throwable
  • 实例字段/方法只能通过实例访问
  • 无需实例即可访问静态字段/方法
  • 静态方法可以通过以下方式之一获取类的实例:
    • 创建new实例
    • 将它作为参数传递
    • 通过static类的字段访问它
    • 接受它作为static类方法的返回值
    • 抓住它作为一个抛出 Throwable

回答by user85421

To access non-static fields (instance variables) you need to have an instance.
Inside a non-static method, thisis used as defaultinstance:

要访问非静态字段(实例变量),您需要有一个实例。
在非静态方法中,this用作默认实例:

class AnyClass  {

    private String nonStaticField = "Non static";

    void nonStaticMethod() {
        this.nonStaticField = "a text";  // accessing field of this
        nonStaticField = "a text";       // same as before
    }
}


Inside a static method there is no thisto use as defaultinstance, but you can1still access instance variables if you provide the instance:

里面一个静态方法没有this为使用默认实例,但你可以1个还访问实例变量,如果你提供的实例:

class AnyClass {

    private String nonStaticField = "Non static";

    static void staticMethod() {
        AnyClass example = new AnyClass();
        example.nonStaticField = "new value for non-static field";
    }
}

1- the field must also be accessibleby Java's access control(declared publicor in the same class ...)

1- 该字段也必须可由Java 的访问控制访问(已声明public或在同一类中...)

回答by Adriaan Koster

Maybe this piece of code will enlighten you:

也许这段代码会启发你:

public class Main {

    private String instanceField = "Joe";

    private void instanceMethod() {
        System.out.println("Instance name=" + instanceField);
    }

    public static void main(String[] args) {

        // cannot change instance field without an instance
        instanceField = "Indy"; // compilation error

        // cannot call an instance method without an instance
        instanceMethod(); // compilation error

        // create an instance
        Main instance = new Main();

        // change instance field
        instance.instanceField = "Sydney";

        // call instance method
        instance.instanceMethod();  
    }
}

So you cannot access instance members without an instance. Within the context of a static method you don't have a reference to an instance unless you receive or create one.

所以你不能在没有实例的情况下访问实例成员。在静态方法的上下文中,除非您接收或创建实例,否则您没有对实例的引用。

Hope this helps.

希望这可以帮助。

回答by Howard

The static method can't access non-static variables outsides because you can use static method without class initialization, but it doesn't work for non-static outside variable. But you can define and use non-static variable in the static method.

静态方法无法访问外部非静态变量,因为您可以使用静态方法而无需类初始化,但它不适用于非静态外部变量。但是您可以在静态方法中定义和使用非静态变量。

回答by venu kumar

One important thing is that unless u create an instance of an class the instance variables don't exist practically it means JVM doesn't that there os an variable like int i unless u create an instance for that class. so, using an instance variable in a static method is an compilation error.

一件重要的事情是,除非您创建类的实例,否则实例变量实际上不存在,这意味着 JVM 不存在像 int i 这样的变量,除非您为该类创建实例。因此,在静态方法中使用实例变量是编译错误。

class A{
    int i;
    static int j;
    static int b(){
        i=10; // cannot be found 
        A a= new A();
        a.i=10;//can be found in a's instance
    }
}

But, we can use instance variables in instance methods because, instance methods are only called when object created so there is no problem in using instance variables inside it.

但是,我们可以在实例方法中使用实例变量,因为只有在创建对象时才会调用实例方法,因此在其中使用实例变量没有问题。

Hope ur clear about these things!

希望你清楚这些事情!