static用法

类变量:用static修饰的变量,也叫静态变量

类变量属于该类,可以被所在类的所有对象实例共享,在类加载的时候就被写入方法区

简单示例:

public class demo1 {
    public static void main(String[] args) {
        child child1 = new child("xixi");
        child1.cnt++;
        child child2 = new child("haha");
        child2.cnt++;
        child child3 = new child("wawa");
        child3.cnt++;
        System.out.println(child.cnt);
    }
}

class child {
    private String name;
    public static int cnt;

    public child(String name) {
        this.name = name;
    }
}

运行结果为3

类方法:用static修饰的方法,也叫静态方法

同理:类方法属于该类,在类加载的时候就被写入方法区

简单示例:

public class demo1 {
    public static void main(String[] args) {
        Student  student1= new Student("lily");
        student1.payfee(100);
        Student  student2= new Student("cathy");
        student2.payfee(200);
        Student.show();
    }
}

class Student{
    String name;
    private static double fee;

    public Student(String name) {
        this.name = name;
    }

    public static void payfee(double fee){
         Student.fee+=fee;
    }

    public static void show() {
        System.out.println(Student.fee);
    }
}

运行结果为300.0

注意点:

类方法中不能用this,super关键字,因为类方法是随着类加载而加载的,而此时类对象还没有创建

类方法中只能访问该方法所在类中的类变量(方法);如果要调用非静态变量(方法),需要先创建对象

而普通方法既可以访问类变量(方法),也可以访问非静态变量(方法)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值