关键字static

来源:互联网 发布:赤月传说2神翼数据 编辑:程序博客网 时间:2024/05/16 09:51
       关键字static:
              静态成员属于类本身的,而不是属于对象,被类的所有对象所共有,即便不创建对象,也可以使用类本身的静态成员。
              静态成员有两种:静态数据成员和静态方法成员。
              使用静态成员的两种方法:类名.静态成员名            。              类对象名.静态成员名
       static方法:
              在静态方法里只能直接调用同类中的其他静态成员(包括变量和方法),而不能直接访问类中的其他非静态成员。这是因为对于非静态变量和方法,需要先创建类的实例对象后才可使用,而静态方法在使用               前不需要创建任何对象。
              静态方法不能以任何方式引用this和super关键字。与上面的道理一样,因为静态方法在使用前不用创建任何实例对象,当静态方法被调用时,this所引用的对象根本就没有产生。
              静态方法只能访问类的静态成员,但非静态方法却可以访问类中所有成员,包括静态成员。

        static的两个应用实例:

//编写使用静态便令统计一个类产生的实例对象的个数的程序class Student{    public static int cnt = 0;    private String sname;    private int sage;    public Student(){        cnt++;    }    public Student(String name , int age){        this.sname = name;        this.sage = age;        cnt++;    }}public class TestStatic_1 {    public static void main(String[] args){        System.out.println("Student.cnt = " +Student.cnt);        Student str1 = new Student("zhangshan",20);        Student str2 = new Student("lisi",30);        System.out.printf("Student 类一共构造了%d个对象",Student.cnt);    }}输出结果:    Student.cnt = 0    Student 类一共构造了2个对象//要求一个类只生成一个对象实例class A{    public int i = 20;    private static A aa = new A();                //aa是否是A对象的属性    private A(){    }    public static A getA(){                        //static一定不能省略        return aa;    }}public class TestStatic_2 {    public static void main(String[] args){        A aa1 = A.getA();        A aa2 = A.getA();        aa1.i = 99;        System.out.printf("%d\n",aa2.i);        if(aa1 == aa2)            System.out.printf("aa1 和 aa2相等\n");        else             System.out.printf("aa1 和aa2不相等");    //    A aa1 = new A();            //error     }}运行结果99aa1 和 aa2相等

看郝斌老师的java视频,从中摘录,很不错的视频。

0 0