静态变量 静态方法

/*
作者:qingfeng
日期:2017/2/20
功能:类变量(静态变量),类方法(静态方法) 统计学费总和
*/

public class Demo3_4
{

    public static void main(String args[]){
        Stu s1=new Stu(23,"qingfeng",200);
        Stu s2=new Stu(20,"lele",123);
        System.out.println(Stu.getTotalFee());
    }
}

class Stu
{
    int age;
    String name;
    int fee;
    static int totalFee;

    public Stu(int age, String name, int fee){
        this.age = age;
        this.name = name;
        totalFee +=fee;
    }
    //类方法(静态方法):用static所有对象共享一个方法,节省栈的开销
    //静态方法不能访问非静态变量
    //java规则:静态变量原则上用静态方法去访问和操作
    public static int getTotalFee(){
        return totalFee;
    }
}


原文地址:https://www.cnblogs.com/qingfengzhuimeng/p/6418548.html