静态字段
静态字段也就是静态属性,在类中对属性定义前加上static
class Person {
public String name;
public int age;
// 定义静态字段number:
public static int number;
}
静态字段的使用
不推荐用实例变量.静态字段去访问静态字段,使用方法如下:
类名.静态字段
比如,要访问number,可以使用:
Person.number = 99;
接口的静态字段
接口(interface)是抽象类,不能定义字段,但是可以有静态字段,并且静态字段必须为final类型。
public interface Person {
public static final int MALE = 1;
public static final int FEMALE = 2;
int MALE = 1; //public static final可以省略
int FEMALE = 2;
}
静态方法
用static修饰的方法称为静态方法。
class Person {
public static int number;
public static void setNumber(int value) {
number = value;
}
}
静态方法的调用
调用静态方法,通过类名就可以实现,调用方法如下:
类名.静态方法名
比如,要调用方法setNumber,可以使用:
Person.setNumber(99);
注意点
静态方法内部,无法访问this变量,也无法访问实例字段,它只能访问静态字段和其他静态方法。
用途
静态方法常用于工具类和辅助方法。
- 静态方法经常用于工具类。例如:
Arrays.sort()
Math.random()
- 静态方法也经常用于辅助方法。注意到Java程序的入口main()也是静态方法。
实例
public class Demo {
public static void main(String[] args) {
//给Person类增加一个静态字段count和静态方法getCount,统计实例的个数
Person p1 = new Person("小周");
System.out.println(Person.getCount()); // 1
Person p2 = new Person("小黄");
System.out.println(Person.getCount()); // 2
Person p3 = new Person("小何");
System.out.println(Person.getCount()); // 3
}
}
public class Person {
String name;
static int count;
public Person(String name) {
count++;
this.name = name;
}
public static int getCount() {
return count;
}
}
参考链接
https://www.liaoxuefeng.com/wiki/1252599548343744/1260464690677856