Java 静态与非静态方法的区别

来源:互联网 发布:shadow web 黑暗网络 编辑:程序博客网 时间:2024/05/01 04:05

博文出处:http://beginnersbook.com/2013/05/static-vs-non-static-methods/


Java is a Object Oriented Programming(OOP) language, which means we need an object to access any method or variable inside or outside the class. However there are some special cases where we don’t need any object (or instance). Yes you heard it right! in order to access static methods we don’t need any object.

Static method example

class StaticDemo{   public static void copyArg(String str1, String str2)   {       //copies argument 2 to arg1       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: XYZSecond 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();

Static methods can’t use non-static(regular) methods

Have a look at the below example:

class Sample{   private int age;   public void setAge(int a)   {      age=a;   }   public int getAge()   {      return age;   }   public static void main(String args[])   {       System.out.println("Age is:"+ getAge());   }}

When you run the above code you would get the following error:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot make a static reference to the non-static method getAge() from the type Sample

Lets discuss why the error? If you think logically then you may notice that Age should be related to an object, means my Age is different than your’s age. So in order to getAge() you should use some object. As a thumb rule non-static method can’t be accessed without an object(or instances).


0 0