Java 静态方法和非静态方法有什么区别?

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

What is the difference between a static method and a non-static method?

java

提问by Sumithra

See the code snippets below:

请参阅下面的代码片段:

Code 1

代码 1

public class A {
    static int add(int i, int j) {
        return(i + j);
    }
}

public class B extends A {
    public static void main(String args[]) {
        short s = 9;
        System.out.println(add(s, 6));
    }
}

Code 2

代码 2

public class A {
    int add(int i, int j) {
        return(i + j);
    }
}

public class B extends A {
    public static void main(String args[]) {
    A a = new A();
        short s = 9;
        System.out.println(a.add(s, 6));
    }
}

What is the difference between these code snippets? Both output 15as an answer.

这些代码片段有什么区别?两者都输出15作为答案。

采纳答案by SapphireSun

A static method belongs to the class itself and a non-static (aka instance) method belongs to each object that is generated from that class. If your method does something that doesn't depend on the individual characteristics of its class, make it static (it will make the program's footprint smaller). Otherwise, it should be non-static.

静态方法属于类本身,非静态(又名实例)方法属于从该类生成的每个对象。如果您的方法所做的事情不依赖于其类的个体特征,请将其设为静态(这将使程序的占用空间更小)。否则,它应该是非静态的。

Example:

例子:

class Foo {
    int i;

    public Foo(int i) { 
       this.i = i;
    }

    public static String method1() {
       return "An example string that doesn't depend on i (an instance variable)";
    }

    public int method2() {
       return this.i + 1; // Depends on i
    }
}

You can call static methods like this: Foo.method1(). If you try that with method2, it will fail. But this will work: Foo bar = new Foo(1); bar.method2();

你可以调用静态方法是这样的:Foo.method1()。如果你用方法 2 尝试,它会失败。但这会起作用:Foo bar = new Foo(1); bar.method2();

回答by Emil

A static method belongs to the class and a non-static method belongs to an object of a class. That is, a non-static method can only be called on an object of a class that it belongs to. A static method can however be called both on the class as well as an object of the class. A static method can access only static members. A non-static method can access both static and non-static members because at the time when the static method is called, the class might not be instantiated (if it is called on the class itself). In the other case, a non-static method can only be called when the class has already been instantiated. A static method is shared by all instances of the class. These are some of the basic differences. I would also like to point out an often ignored difference in this context. Whenever a method is called in C++/Java/C#, an implicit argument (the 'this' reference) is passed along with/without the other parameters. In case of a static method call, the 'this' reference is not passed as static methods belong to a class and hence do not have the 'this' reference.

静态方法属于类,非静态方法属于类的对象。也就是说,非静态方法只能在它所属的类的对象上调用。然而,静态方法既可以在类上也可以在类的对象上调用。静态方法只能访问静态成员。非静态方法可以访问静态和非静态成员,因为在调用静态方法时,类可能不会被实例化(如果它是在类本身上调用的)。在另一种情况下,非静态方法只能在类已经实例化时调用。静态方法由类的所有实例共享。这些是一些基本的区别。我还想指出在这种情况下经常被忽视的差异。每当在 C++/Java/C# 中调用方法时,都会传递一个隐式参数(“this”引用)和/不带其他参数。在静态方法调用的情况下,“this”引用不会作为属于类的静态方法传递,因此没有“this”引用。

Reference:Static Vs Non-Static methods

参考静态与非静态方法

回答by Musaffir

Basic difference is non static members are declared with out using the keyword 'static'

基本区别是非静态成员是在不使用关键字“static”的情况下声明的

All the static members (both variables and methods) are referred with the help of class name. Hence the static members of class are also called as class reference members or class members..

所有静态成员(变量和方法)都在类名的帮助下引用。因此类的静态成员也称为类引用成员或类成员。

In order to access the non static members of a class we should create reference variable . reference variable store an object..

为了访问类的非静态成员,我们应该创建引用变量。引用变量存储一个对象..

回答by Rahul Saxena

A static method belongs to the class and a non-static method belongs to an object of a class. I am giving one example how it creates difference between outputs.

静态方法属于类,非静态方法属于类的对象。我举了一个例子,它如何在输出之间产生差异。

public class DifferenceBetweenStaticAndNonStatic {

  static int count = 0;
  private int count1 = 0;

  public DifferenceBetweenStaticAndNonStatic(){
    count1 = count1+1;
  }

  public int getCount1() {
    return count1;
  }

  public void setCount1(int count1) {
    this.count1 = count1;
  }

  public static int countStaticPosition() {
    count = count+1; 
    return count;
    /*
     * one can not use non static variables in static method.so if we will
     * return count1 it will give compilation error. return count1;
     */
  }
}

public class StaticNonStaticCheck {

  public static void main(String[] args){
    for(int i=0;i<4;i++) {
      DifferenceBetweenStaticAndNonStatic p =new DifferenceBetweenStaticAndNonStatic();
      System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.count);
        System.out.println("static count position is " +p.getCount1());
        System.out.println("static count position is " +DifferenceBetweenStaticAndNonStatic.countStaticPosition());

        System.out.println("next case: ");
        System.out.println(" ");

    }
}

}

}

Now output will be:::

现在输出将是:::

static count position is 0
static count position is 1
static count position is 1
next case: 

static count position is 1
static count position is 1
static count position is 2
next case: 

static count position is 2
static count position is 1
static count position is 3
next case:  

回答by VikingGlen

Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:

如果您只有一个实例(情况、环境)要使用该方法,并且不需要多个副本(对象),则静态方法很有用。例如,如果您正在编写一种方法,该方法登录到一个且只有一个网站,下载天气数据,然后返回值,您可以将其编写为静态的,因为您可以在该方法中硬编码所有必要的数据,并且你不会有多个实例或副本。然后,您可以使用以下方法之一静态访问该方法:

MyClass.myMethod();
this.myMethod();
myMethod();

Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:

如果您打算使用您的方法创建多个副本,则使用非静态方法。例如,如果您想从波士顿、迈阿密和洛杉矶下载天气数据,并且如果您可以在您的方法中这样做而不必为每个单独的位置单独定制代码,那么您可以非静态地访问该方法:

MyClass boston = new MyClassConstructor(); 
boston.myMethod("bostonURL");

MyClass miami = new MyClassConstructor(); 
miami.myMethod("miamiURL");

MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");

In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.

在上面的示例中,Java 通过相同的方法创建了三个单独的对象和内存位置,您可以使用“boston”、“miami”或“losAngeles”引用单独访问这些对象和内存位置。您无法静态访问上述任何内容,因为 MyClass.myMethod(); 是对方法的通用引用,而不是对非静态引用创建的单个对象的引用。

If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.

如果您遇到访问每个位置的方式或返回数据的方式大不相同的情况,以至于您无法编写“一刀切”的方法而不跳很多圈,那么您可以更好通过编写三个单独的静态方法来实现您的目标,每个位置一个。

回答by Alex Vaz

Well, more technically speaking, the difference between a static method and a virtual method is the way the are linked.

好吧,从技术上讲,静态方法和虚拟方法之间的区别在于它们的链接方式。

A traditional "static" method like in most non OO languages gets linked/wired "statically" to its implementation at compile time. That is, if you call method Y() in program A, and link your program A with library X that implements Y(), the address of X.Y() is hardcoded to A, and you can not change that.

大多数非面向对象语言中的传统“静态”方法在编译时“静态”链接/连接到其实现。也就是说,如果您在程序 A 中调用方法 Y(),并将您的程序 A 与实现 Y() 的库 X 链接起来,则 XY() 的地址被硬编码到 A,并且您无法更改它。

In OO languages like JAVA, "virtual" methods are resolved "late", at run-time, and you need to provide an instance of a class. So in, program A, to call virtual method Y(), you need to provide an instance, B.Y() for example. At runtime, every time A calls B.Y() the implementation called will depend on the instance used, so B.Y() , C.Y() etc... could all potential provide different implementations of Y() at runtime.

在像 JAVA 这样的 OO 语言中,“虚拟”方法在运行时被“延迟”解析,您需要提供一个类的实例。因此,在程序 A 中,要调用虚拟方法 Y(),您需要提供一个实例,例如 BY()。在运行时,每次 A 调用 BY() 调用的实现将取决于使用的实例,因此 BY() 、 CY() 等...都可能在运行时提供 Y() 的不同实现。

Why will you ever need that? Because that way you can decouple your code from the dependencies. For example, say program A is doing "draw()". With a static language, thats it, but with OO you will do B.draw() and the actual drawing will depend on the type of object B, which, at runtime, can change to square a circle etc. That way your code can draw multiple things with no need to change, even if new types of B are provided AFTER the code was written. Nifty -

为什么你会需要那个?因为这样您就可以将代码与依赖项分离。例如,假设程序 A 正在执行“draw()”。使用静态语言,仅此而已,但是使用 OO,您将执行 B.draw() 并且实际绘图将取决于对象 B 的类型,它在运行时可以更改为正方形等。这样您的代码就可以无需更改即可绘制多个内容,即使在编写代码后提供了新类型的 B。俏皮——

回答by murthy naika k

Generally

一般来说

static: no need to create object we can directly call using

static: 不需要创建我们可以直接调用的对象

ClassName.methodname()

Non Static: we need to create a object like

非静态:我们需要创建一个像

ClassName obj=new ClassName()
obj.methodname();

回答by EngineerEngin

If your method is related to the object's characteristics, you should define it as non-static method. Otherwise, you can define your method as static, and you can use it independently from object.

如果您的方法与对象的特性有关,则应将其定义为非静态方法。否则,您可以将方法定义为静态方法,并且可以独立于对象使用它。

回答by Ujjaval Moradiya

Another scenario for Static method.

静态方法的另一个场景。

Yes, Static method is of the class not of the object. And when you don't want anyone to initialize the object of the class or you don't want more than one object, you need to use Private constructorand so the static method.

是的,静态方法属于类而不是对象。当你不希望任何人初始化类的对象或者你不想要多个对象时,你需要使用Private 构造函数等静态方法。

Here, we have private constructor and using static method we are creating a object.

在这里,我们有私有构造函数并使用静态方法创建一个对象。

Ex::

前任::

public class Demo {

        private static Demo obj = null;         
        private Demo() {
        }

        public static Demo createObj() {

            if(obj == null) {
               obj = new Demo();
            }
            return obj;
        }
}

Demo obj1 = Demo.createObj();

演示 obj1 = Demo.createObj();

Here, Only 1 instance will be alive at a time.

在这里,一次只有 1 个实例处于活动状态。

回答by paxmao

Sometimes, you want to have variables that are common to all objects. This is accomplished with the static modifier.

有时,您希望拥有所有对象共有的变量。这是通过静态修饰符完成的。

i.e. class human - number of heads (1) is static, same for all humans, however human - haircolor is variable for each human.

即类人类 - 头数 (1) 是静态的,对所有人都是一样的,但是人类 - 每个人的头发颜色都是可变的。

Notice that static vars can also be used to share information across all instances

请注意,静态变量也可用于在所有实例之间共享信息