1. 用于记录创建了多少个实例对象
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle(6.5);
Circle c2 = new Circle(6.3);
System.out.println(Circle.getTotal());
}
}
class Circle{
private double radius;
private static String info = "我是一个圆";
private static int total = 0;
public Circle(double radius) {
this.radius = radius;
total++;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public static String getInfo() {
return info;
}
public static void setInfo(String info) {
Circle.info = info;
}
public static int getTotal() {
return total;
}
public static void show() {
System.out.println(info);
}
@Override
public String toString() {
return "Circle [radius=" + radius + "]";
}
}
2.什么情况下我们可以把变量或者方法声明成static方法呢
- 当属性为了所有实例都公用一个属性的时候,如:所有中国人实例,都只有一个国籍,π不会因为情况而改变,所有人都遵循这个标准。
- 当方法不依赖于具体对象的不同而不同,如:数组获取最大值的方法,其不会因为对象的不同而改变,它只是提供了一个 int 数组获取最大值功能而已。
public static int getMax(int [] arr){
int max = arr[0];
for(int i = 1; i < arr.length; i++){
if(max < a[i]){
max = a[i];
}
}
return max;
}