类方法是属于所有对象实例的其形式如下:
访问修饰符 static 数据返回类型 方法名(){}
类方法中不能访问非静态变量 使用类名.类方法名 或者 对象名.类方法名
定义一个学生类,统计学生共交了多少钱?
public class StuDemo{ public static void main(String[] args){ Student stu1 = new Student(29,"aa",365); Student stu2 = new Student(29,"bb",360); System.out.println(stu2.getTotalFee()); } } //学生 class Student{ int age; String name; int fee; static int totalFee; public Student(int age,String name,int fee){ this.age = age; this.name = name; totalFee += fee; } //返回总学费[这是一个静态方法] //类变量原则上用类方法去访问和操作 public static int getTotalFee(){
return totalFee; } }
类方法属于与类相关的,公共的方法
实例方法属于每个对象个体方法
类方法可以通过类名.类方法名直接访问