类方法也叫静态方法
定义形式:
同类变量一样:可以使用类名.类方法名调用,也可以对象名.类方法名调用(需要遵守访问修饰符规则)
案例了解:
public class StaticMethod {
public static void main(String[] args) {
Stu xm = new Stu("小明");
xm.payFee(200);
Stu xh = new Stu("小红");
xh.payFee(200);
Stu.showFee();
}
}
class Stu{
private static double fee;//类变量
String name;
public Stu(String name) {
this.name = name;
}
public static void payFee(double fee){//类方法
Stu.fee+=fee;
}
public static void showFee(){//类方法
System.out.println(Stu.fee);
}
}
输出结果:400
就像要求两个数的和,如果这个方法设计成实例方法,那么每创建一个对象,就要浪费内存去存放这个方法,而将它设计出静态方法时,就不会每次实例化对象都要一点内存。
1.看看输出的是什么?
publi class Test{
static int count = 9 ;
public void count(){
System.out.println(count++)
}
public static void main(String[]args){
new Test.count();
new Test.count();
System.out.println(count)
}
}
输出结果: 9 10 11(后++,先运算 后自增)
2.查找出下面代码的错误。且修改,并看看输出结果
public class Person {
private int id ;
private static int total;
public static int getTotal(){
//id++;静态只能调用静态
return total;
}
public Person(){
total++;
id = total;
}
}
class testPerson{
public static void main(String[] args) {
System.out.println(Person.getTotal());//输出 0
Person p1 = new Person();//使用构造器,+1
System.out.println(Person.getTotal());//输出 1
}
}
3.查找出下面代码的错误。且修改,并看看最后total的值是多少
public class Person {
private int id ;
private static int total;
public static void setTotal(int total){
//this.total = total,静态方法不能使用有关对象的关键字
Person.total = total;
}
public Person(){
total++;
id = total;
}
}
class testPerson{
public static void main(String[] args) {
Person.setTotal(3);
new Person();
}
}
最后total的值是 4