java static关键字经典的应用

1. 用于记录创建了多少个实例对象

//static 的一个应用
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());//2
		
	}
}
class Circle{
	private double radius;//半径
	private static String info = "我是一个圆";
	//因为total是static的,在内存中只有一个,所以可以用来记录创建的对象的个数
	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方法呢

  1. 当属性为了所有实例都公用一个属性的时候,如:所有中国人实例,都只有一个国籍,π不会因为情况而改变,所有人都遵循这个标准。
  2. 当方法不依赖于具体对象的不同而不同,如:数组获取最大值的方法,其不会因为对象的不同而改变,它只是提供了一个 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值