类方法

Java中规则:类变量原则上用类方法去访问和操作

类方法是属于 所有对象实例的 形式如下:
访问修饰符 static 数据返回类型 方法名(){}
注意:类方法中不能访问非静态变量(类变量)
 
统计学费总和:
public class Demo3_2 {

public static void main(String []args)
{

Stu stu1=new Stu(23,"aa",240);
Stu stu2=new Stu(24,"aa",348);
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;

}
//返回总学费【这是一个类方法(即静态方法)】

public static int getTotalFee()
{
//注意:类方法中不能访问非静态变量(类变量),例如,在此方法中不能访问age name变量
//但是普通方法中可以访问静态变量
return totalFee;
}
}

原文地址:https://www.cnblogs.com/fengxiaolan/p/5874513.html