Java 静态方法和非静态方法之间的区别是什么?

Java 静态方法和非静态方法之间的区别是什么?,java,Java,请参见下面的代码片段: 代码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)); } } 代码2 publi

请参见下面的代码片段:

代码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));
    }
}
代码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));
    }
}
这些代码片段之间有什么区别?两者都输出
15
作为答案


静态方法属于该类 非静态方法属于 类的对象。就是一个 只能调用非静态方法 在类的对象上 属于。静态方法可以 然而,这两个词在课堂上都可以称为 以及类的对象。A. 静态方法只能访问静态 成员。非静态方法可以 访问静态和非静态 因为当时 调用静态方法时,类 可能未实例化(如果是 调用类本身)。在 在其他情况下,可以使用非静态方法 仅当类已 已经实例化了。静电计 方法由的所有实例共享 这个班。这些是一些基本的 差异。我也想 指出一个经常被忽视的差异 在这方面。每当一个方法 在C++/Java/C#中调用,隐式 参数(“this”引用)为 与另一个一起传递/没有传递 参数。如果是静态方法 调用时,“this”引用不可用 作为静态方法传递的方法属于 类,因此没有“this” 参考资料


参考

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

例如:

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
    }
}

您可以这样调用静态方法:
Foo.method1()
。如果您尝试使用方法2,它将失败。但这会起作用:
foobar=newfoo(1);方法2()

基本区别在于,使用关键字“static”声明非静态成员时不使用out

所有静态成员(变量和方法)都通过类名进行引用。 因此,类的静态成员也称为类引用成员或类成员

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

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

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(" ");

    }
}

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

MyClass.myMethod();
this.myMethod();
myMethod();
如果要使用方法创建多个副本,则使用非静态方法。例如,如果您希望从波士顿、迈阿密和洛杉矶下载天气数据,并且如果您可以从方法中下载,而不必为每个单独的位置单独自定义代码,则可以非静态地访问该方法:

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

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

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


如果您遇到一种情况,即访问每个位置的方式或返回数据的方式完全不同,以至于您无法编写一个“一刀切”的方法而不跳过很多障碍,那么您可以通过编写三个单独的静态方法来更好地实现您的目标,每个位置一个,更严格地说,静态方法和虚拟方法的区别在于它们之间的链接方式

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

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

你为什么需要这个?因为这样可以将代码与依赖项解耦。例如,假设程序A正在执行“draw()”。使用静态语言,就是这样,但使用OO,您将执行B.draw(),实际绘制将取决于对象B的类型,在运行时,对象B可以更改为正方形等。这样,您的代码可以绘制多个对象,而无需更改,即使在编写代码后提供了新类型的B。漂亮-一般来说

静态:无需创建对象,我们可以使用

ClassName.methodname()
非静态:我们需要创建一个类似

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

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

静态方法的另一个场景

是的,静态方法属于类而不是对象
ClassName obj=new ClassName()
obj.methodname();
public class Demo {

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

        public static Demo createObj() {

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

 public static void copyArg(String str1, String str2)
    {
       str2 = str1;
       System.out.println("First String arg is: "+str1);
       System.out.println("Second String arg is: "+str2);
    }
    public static void main(String agrs[])
    {
      //StaticDemo.copyArg("XYZ", "ABC");
      copyArg("XYZ", "ABC");
    }
}
class Test
{
    public void display()
    {
       System.out.println("I'm non-static method");
    }
    public static void main(String agrs[])
    {
       Test obj=new Test();
       obj.display();
    }
}
I'm non-static method
StaticDemo.copyArg(s1, s2);
copyArg(s1, s2);
Test obj = new Test();
- First we must know that the diff bet static and non static methods 
is differ from static and non static variables : 

- this code explain static method - non static method and what is the diff 

    public class MyClass {
        static {
            System.out.println("this is static routine ... ");

        }
          public static void foo(){
            System.out.println("this is static method ");
        }

        public void blabla(){

         System.out.println("this is non static method ");
        }

        public static void main(String[] args) {

           /* ***************************************************************************  
            * 1- in static method you can implement the method inside its class like :  *       
            * you don't have to make an object of this class to implement this method   *      
            * MyClass.foo();          // this is correct                                *     
            * MyClass.blabla();       // this is not correct because any non static     *
            * method you must make an object from the class to access it like this :    *            
            * MyClass m = new MyClass();                                                *     
            * m.blabla();                                                               *    
            * ***************************************************************************/

            // access static method without make an object 
            MyClass.foo();

            MyClass m = new MyClass();
            // access non static method via make object 
            m.blabla();
            /* 
              access static method make a warning but the code run ok 
               because you don't have to make an object from MyClass 
               you can easily call it MyClass.foo(); 
            */
            m.foo();
        }    
    }
    /* output of the code */
    /*
    this is static routine ... 
    this is static method 
    this is non static method 
    this is static method
    */

 - this code explain static method - non static Variables and what is the diff 


     public class Myclass2 {

                // you can declare static variable here : 
                // or you can write  int callCount = 0; 
                // make the same thing 
                //static int callCount = 0; = int callCount = 0;
                static int callCount = 0;    

                public void method() {
                    /********************************************************************* 
                    Can i declare a static variable inside static member function in Java?
                    - no you can't 
                    static int callCount = 0;  // error                                                   
                    ***********************************************************************/
                /* static variable */
                callCount++;
                System.out.println("Calls in method (1) : " + callCount);
                }

                public void method2() {
                int callCount2 = 0 ; 
                /* non static variable */   
                callCount2++;
                System.out.println("Calls in method (2) : " + callCount2);
                }


            public static void main(String[] args) {
             Myclass2 m = new Myclass2();
             /* method (1) calls */
             m.method(); 
             m.method();
             m.method();
             /* method (2) calls */
             m.method2();
             m.method2();
             m.method2();
            }

        }
        // output 

        // Calls in method (1) : 1
        // Calls in method (1) : 2
        // Calls in method (1) : 3
        // Calls in method (2) : 1
        // Calls in method (2) : 1
        // Calls in method (2) : 1