类变量:用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关键字,因为类方法是随着类加载而加载的,而此时类对象还没有创建
类方法中只能访问该方法所在类中的类变量(方法);如果要调用非静态变量(方法),需要先创建对象
而普通方法既可以访问类变量(方法),也可以访问非静态变量(方法)