Java中static静态与非静态的区别

先前看到一个技术大牛写了一个关于静态成员与非静态成员,静态方法和非静态方法的各自区别,觉得挺好的,在这里写一个小程序来说明这些区别。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package com.liaojianya.chapter5;
/**
 * This program will demonstrate the use of static method.
 * @author LIAO JIANYA
 *
 */
public class StaticTest
{
    public static void main(String[] args)
    {
        System.out.println("用对象调用非静态方法");
        MyObject obj = new MyObject();
        obj.print1();
        System.out.println("用类调用静态方法");
        MyObject.print2();
         
    }
 
}
 
class MyObject
{
    private static String str1 = "staticProperty";
    private String str2 = "nonstaticProperty";
     
    public MyObject()
    {
         
    }
     
    public void print1()
    {
        System.out.println(str1);//非静态方法可以访问静态域
        System.out.println(str2);//非静态方法可以访问非静态域
        print2();//非静态方法可以访问静态方法
    }
     
    public static void print2()
    {
        System.out.println(str1);//静态方法可以访问静态域
//      System.out.println(str2);  //静态方法不可以访问非静态域
//      print1();//静态方法不可以访问非静态方法
    }
}

  

 输出结果:
用对象调用非静态方法
staticProperty
nonstaticProperty
staticProperty
用类调用静态方法
staticProperty

该注释部分如果去掉注释符号,就会两个报错:

第一个注释去掉后引起的错误1:

Cannot make a static reference to the non-static field str2

第二个注释去掉后引起的错误2:

Cannot make a static reference to the non-static method print1() from the type MyObject

结论:静态的方法不能访问非静态的成员变量;静态的方法同样不能访问非静态的方法。

其实就是一句话:静态的不能访问非静态的,而非静态的可以访问静态的并且可以访问非静态的。

同时:静态的方法是可以通过类名来直接调用,无需对象调用,从而减少了实例化的开销。

 

posted @ 2016-07-07 22:04  3分对错7分做作  阅读(592)  评论(0编辑  收藏  举报