static

来源:互联网 发布:战争潜力知乎 编辑:程序博客网 时间:2024/06/07 14:06

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

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();//静态方法不可以访问非静态方法}}

  

 输出结果:
用对象调用非静态方法staticPropertynonstaticPropertystaticProperty用类调用静态方法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

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

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

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

 续写程序1:

package com.liaojianya.chapter1;/** * This program demonstrates the use of constant and final * @author LIAO JIANYA * */public class TestFinal4_1{static final int YEAR = 365; //static 是因为main是静态的方法,所以只能访问静态域。public static void main(String[] args){System.out.println("Two years are: " + 2 * YEAR + " days");}}

  

0 0