关键字static

         关键字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 
    }
}

运行结果
99
aa1 和 aa2相等

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值