What is the difference between a static method and

2018-12-31 06:37发布

See the code snippets below:

Code 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

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 15 as an answer.

标签: java
13条回答
柔情千种
2楼-- · 2018-12-31 07:35

Static method example

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

Output:

First String arg is: XYZ

Second String arg is: XYZ

As you can see in the above example that for calling static method, I didn’t even use an object. It can be directly called in a program or by using class name.

Non-static method example

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

Output:

I'm non-static method

A non-static method is always be called by using the object of class as shown in the above example.

Key Points:

How to call static methods: direct or using class name:

StaticDemo.copyArg(s1, s2);

or

copyArg(s1, s2);

How to call a non-static method: using object of the class:

Test obj = new Test();
查看更多
登录 后发表回答