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

博文出处: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: 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();

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).


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值